好吧,我的任务是,我必须按照从大到小的顺序对一系列随机数进行排序。随机数来自 indexOfMaxInRange,取最大数的索引返回。在 swapElements 中,它基本上必须将最高元素的索引交换到 a[0],第二高到 a[1],依此类推。这两个方法是通过 sortarray 传递的。请给我一些关于如何完成这个以及我做错了什么的意见,谢谢。PS:由于各种原因,例如打印,并非所有内容都在代码中被调用。
这是我的代码:
public static void main(String[] args) {
int[] array = randomIntArray (10);
int index = indexOfMaxInRange (array, -5, 15 );
swapElement (array, index, 0);
}
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){ //Find the index of the largest element
int [] b = new int [a.length];
int index = 0;
for (int i = 0; i < a.length-1; i++){
if (a[i] >= low && a[i] < high)index++;
if (a[i] > a[i+1]){
b[i] = a[i];
}
System.out.println (b[i]+"\t"+ (index));
}
return index ;
}
public static int swapElement (int []a, int index , int i){ // Swap the element within the array
int temp = 0;
System.out.println ();
for ( i = 0; i <a.length; i++){
temp = index;
a[i] = a[a.length - i - 1];
temp = a[a.length - i - 1];
System.out.println (temp + "\t"+ index);
}
return temp;
}
public static void sortArray (int[] array){
for (int i = 0; i <array.length; i++){
int index = indexOfMaxInRange (array, -5, 15 );
swapElement (array, index, 0);
System.out.println (); // This will print out the newly arranged order of the numbers.
}
}