对于这个任务,我无法让最后一个方法再次循环并找到随机数系列中的下一个最大元素。解决这个问题的一些输入会很棒。谢谢你。
公共静态无效主要(字符串[]参数){
int[] array = randomIntArray (10);
sortArray (array);
}
public static int randomInt (int low, int high){ // Create a serie of random numbers
int x = 0;
for (int i = 0; i < 10; i++){
x = (int)(Math.random ()* (high - low) +low);
}
return x;
}
public static int[] randomIntArray (int n) { // Size of array
int[] a = new int [n];
for (int i = 0; i <a.length; i++){
a[i] = randomInt (-5, 15);
}
return a;
}
public static int indexOfMaxInRange (int[] a, int low , int high){
int index = low;
for (int i = low +1; i < high; i++){
if (a[i] > a[index]){ // If the position of i is greater than index
index = i; // then index will equal that position with the highest element
}
}
return index;
}
public static int swapElement (int []a, int index , int i){
int tmp =0;
for(i = 0; i < (a.length); i++) {
tmp = index;
a[i]= a[tmp] ;
}
return a[tmp] ;
}
public static void sortArray (int[] array){ //The sortArray calls the indexOfMaxInRange to get the index of the largest element, then uses swapElement to swap that index's position to position a[i].
for (int b= 0; b <array.length; b++){
System.out.println (array[b]+"\t"+ b); // Print out original list of random numbers
}
System.out.println ();
for (int i = 0; i <array.length; i++){
int index = indexOfMaxInRange (array, 0, 10 );
int sort = swapElement (array, index, 0);
System.out.println (sort+"\t"+ i);
}
}