c++ - Iteration on Quick Sort -
i trying implement quick sort now. but, have problem loop part below
for (int current = 0; current <= high - 1; current++)
when initialize 'current' statement 0, show nothing on screen when run it. then, try replace 'low' argument in implementation provided , run appropriately.
what want ask is, why doesn't work when initialize loop statement 0, same value assigned 'low' parameter? have tried initialize new variable 0 , use variable loop, give same result when directly assign loop statement 0. answer.
here code:
int partition(int arr[], int low, int high) { int pivot = arr[high]; int index = (low - 1); (int current = low; current <= high - 1; current++) { if (arr[current] <= pivot) { index++; swap(arr[index], arr[current]); } } swap(arr[index+1], arr[high]); return (index + 1); } void quicksort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quicksort(arr, low, pi - 1); quicksort(arr, pi + 1, high); } } int main() { int arr[] = { 3, 4, 2, 5, 1 }; int n = sizeof(arr)/sizeof(arr[0]); quicksort(arr, 0, n-1); (int = 0; < n; i++) { cout << arr[i] << " "; } }
low
0 in first call partition
; takes different values in other calls. note when quicksort
calls second time, low
assigned pi + 1
.
print out in beginning of partition
observe known not-too-large array - should educational exercise in general. mean make first line of partition
:
cout << "low = " << low << "\n";
Comments
Post a Comment