Specify array by console input:
import java.util.Scanner; // import library
private static Scanner scanner = new Scanner(System.in);
public static int[] getIntegers(int number){
int[] values = new int[number];
for (int i=0; i<values.length; i++){
values[i] = scanner.nextInt();
}
return values;
}
int myIntegers[] = getIntegers(5); //create integer array using method
Sorting algorithms:
Bubble Sort- Ascending
for(int i = arr.length-1 ; i > 0 ; i--){
for(int j = 0 ; j < i ; j++){
if( arr[j] > arr[j+1] ){ // descending order if( arr[j] <arr[j+1] )
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
Selection sort - ascending
for (int i=0; i <arr.length -1;i++){ int min_i=i; for (int j=i+1;j<arr.length;j++){ if(arr[j]<arr[min_i]){
// descending order if(arr[j]>arr[min_i])min_i=j; } } int temp=arr[i]; arr[i]=arr[min_i]; arr[min_i]=temp; }
Комментариев нет:
Отправить комментарий