出於某種原因,我的數組的中間元素仍然無序......我不知道爲什麼,但我只是中間元素仍然未排序
public class QuickSort {
public int a[];
public QuickSort(int[] a) {
this.a = a;
}
private void swap(int pos1, int pos2) {
int t = a[pos1];
a[pos1] = a[pos2];
a[pos2] = t;
}
private int partition(int low, int high) {
int i = low, j = low + 1, pivot = low;
while (j < high) {
if (a[j] <= a[pivot]) {
swap(++i, j);
}
j++;
}
swap(i, pivot);
return i;
}
private void sort(int low, int high) {
int i;
if (low >= high)
return;
else {
i = partition(low, high);
sort(i + 1, high);
sort(low, i - 1);
}
}
public String toString() {
StringBuilder sb = new StringBuilder("");
for (int i : a) {
sb.append(i);
sb.append("\n");
}
return sb.toString();
}
private static int[] generateRandomNumbers(int s) {
int a[] = new int[s];
for (int i = 0; i < s; i++) {
a[i] = new Random().nextInt(50);
}
return a;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of elements");
int s = sc.nextInt();
QuickSort obj = new QuickSort(generateRandomNumbers(s));
System.out.println(obj.toString());
obj.sort(0, s - 1);
System.out.println("\n");
System.out.println(obj.toString());
}
}
數組充滿了隨機生成的數字,這是一個標準的快速排序算法 任何幫助,將不勝感激,我是一個新手程序員,試圖調試的時間太長了這段代碼...
你可以給你使用這個與和O的一個數組的例子本安輸出? –
我隨機生成數組...... ill編輯我的問題以添加整個代碼... –
您的支點是第一個元素。它不應該在中間更多嗎? – TedTrippin