【发布时间】:2011-12-29 20:13:22
【问题描述】:
我需要创建一个随机的 int 数组,并按我自己的类对其进行排序。这是我制作数组的地方:
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 类)。我的问题是如何从同一个文件夹中实现这个类,以便我可以使用它。这是快速排序类:
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;
}
}
}
抱歉所有信息。
【问题讨论】:
-
同一个文件夹是什么意思?
-
list.QuickSort()不是有效的 Java。我建议您包含一个带有可编译代码的示例.. -
你可能想打电话给
QuickSort.quickSort(list) -
quicksort 只是我试图从 MyProgram9 类中调用的另一个类。我该怎么做呢