我需要創建一個隨機數組的int並讓它按照我自己的類進行排序。這裏是我的陣列:創建一個int類型的隨機數組。 Java
public class MyProgram9{
public static void main(String[] args){
int[] list = new int[10];
for (int i=0; i<10; i++){
int n = (int)(Math.random()*9 + 1);
list[i] = n;
System.out.println(list[i] + " ");
}
list.QuickSort();
}
}
然後我試圖用另一個類對它進行排序(QuickSort類)。我的問題是如何從同一個文件夾實現這個類,以便我可以使用它。這裏是quickSort類:
public class QuickSort{
public static void quickSort(int[] list){
quickSort(list, 0, list.length - 1);
}
private static void quickSort(int[] list, int first, int last) {
if (last > first) {
int pivotIndex = partition(list, first, last);
quickSort(list, first, pivotIndex - 1);
quickSort(list, pivotIndex + 1, last);
}
}
/** Partition the array list[first..last] */
private static int partition(int[] list, int first, int last) {
int pivot = list[first]; // Choose the first element as the pivot
int low = first + 1; // Index for forward search
int high = last; // Index for backward search
while (high > low) {
// Search forward from left
while (low <= high && list[low] <= pivot)
low++;
// Search backward from right
while (low <= high && list[high] > pivot)
high--;
// Swap two elements in the list
if (high > low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while (high > first && list[high] >= pivot)
high--;
// Swap pivot with list[high]
if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
}
else {
return first;
}
}
}
對不起,所有的信息。
更換你的主要方法的最後一行是什麼您從同一個文件夾意思? – Tudor
'list.QuickSort()'不是有效的Java。我建議你包括一個編譯代碼示例.. – mre
聽起來像作業... – Laf