所以這個程序的目的是有選擇地排序從最大到最小的整數隨機數組。要做到這一點,我需要繼續交換具有最大元素的第一個元素。我認爲我的方法是正確的,但我對Java相當陌生,不確定要在main中調用什麼才能正確執行我的方法。先謝謝你!Java程序的排序隨機數組
package sortarray;
public class SortArray {
public static int randomInt(int low, int high) {
double e;
double x=Math.random();
e=low+x*(high-low);
return (int)e;
}
public static int[] randomIntArray(int n) {
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 < a.length; i++) {
if (a[i] > a[index]) {
index = i;
}
}
return index;
}
public static void swapElement(int[] a, int index1, int index2) {
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public static void sort(int[] a) {
int length = a.length;
//use length-1 because do not need to swap last element with itself
for (int i = 0; i < length-1; i++) {
int indexOfMax = indexOfMaxInRange(a, i, length-1);
swapElement(a, i, indexOfMax);
}
}
public static void printArray(int[] a) {
for(int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}
public static void main(String[] args) {
int[] array = randomIntArray(30);
printArray();
}
}
'Arrays.sort(array);' – user2173372