[英]How should I fix this quicksort function?
遵循有關quicksort算法的在線資源,我重構了以下功能:
void quickSort(int *array, int arrayLength, int first, int last) {
int pivot, j, i, temp;
if (first < last) {
pivot = first;
i = first;
j = last;
while (i < j) {
while (array[i] <= array[pivot] && i < last) {
i++;
}
while (array[j] > array[pivot]) {
j--;
}
if (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
temp = array[pivot];
array[pivot] = array[j];
array[j] = temp;
quickSort(array, arrayLength, first, j-1);
quickSort(array, arrayLength, j+1, last);
}
printBars(array, arrayLength);
}
為了了解它是如何printBars
,我編寫了一個printBars
過程,該過程可以像這樣打印數組的內容
int bars[] = {2, 4, 1, 8, 5, 9, 10, 7, 3, 6};
int barCount = 10;
printBars(bars, barCount);
我在前面提到的數組bars[]
上運行quickSort
之后的最終結果是此圖形
quickSort(bars, barCount, 1, 10);
10
去了哪里? 0
(原始數組沒有)? 數組索引從零開始。 所以你只想更正你的電話
quickSort(bars, barCount, 0, 9);
或最好
quickSort(bars, barCount, 0, barCount - 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.