0

QuickSort Algorithm

Hi there, I am hoping to fully understand the quicksort algorithm. I recently came across a video on YouTube, and the algorithm that was used makes sense, there are some cases where the array is not after the quicksort function has been called. If anyone can point out the flaw in the code/algorithm, it will be much appreciated! Thank You! Code: void QuickSort(int arr[], int left, int right) { int l = left; int r = right; int pivot = (left + right) / 2; while (l <= r) { while (arr[l] < arr[pivot]) { l++; } while (arr[r] > arr[pivot]) { r--; } if (l <= r) { swap(arr[l], arr[r]); l++; r--; } } if (left < r) { QuickSort(arr, left, r); } if (l < right) { QuickSort(arr, l, right); } } Output: The array is filled with random values: 7 8 9 2 9 4 6 6 1 2 The array after QuickSort function call: 1 2 2 7 8 4 6 6 9 9

19th Jul 2018, 9:42 PM
Tanjid Shuhag
Tanjid Shuhag - avatar
3 odpowiedzi
+ 2
Tanjid Shuhag save it in a playground code and share the link. Also include the languahe in the question tag please.
19th Jul 2018, 11:06 PM
Manual
Manual - avatar
+ 2
Once you pick a pivot everything lower needs to be to the left and higher to the right. You are only swapping two elements at most. Take a look at the code here. https://www.geeksforgeeks.org/quick-sort/
20th Jul 2018, 2:32 AM
John Wells
John Wells - avatar
0
https://code.sololearn.com/cADa9eHkYPe5/?ref=app
20th Jul 2018, 2:31 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar