#include <stdio.h>
void swap(int arr[], int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void quick(int arr[], int low, int high) {
if(low>=high) return;
int p = high;
int l = low;
int r = high;
while(l<r){
while(arr[l]<=arr[p] && l<r) l++;
while(arr[r]>arr[p] && r>l) r--;
swap(arr, l, r);
} swap(arr, l, p);
quick(arr, low, r-1);
quick(arr, r+1, high);
}
int main() {
int arr[] = {91,3,6,21,1,5,8,3,21,5,65,23,87,45,88,2};
quick(arr, 0, (sizeof(arr)/sizeof(arr[0])-1));
for(int i=0; i<(sizeof(arr)/sizeof(arr[0])-1); i++) {
printf("%d ",arr[i]);
}
}
this piece of quicksorting code does not sort the first element if its the largest in the list. I tried to solve it by taking r=high-1 but that results in the array not being sorted at all. I do not understand why either of them are happening
I followed an online tutorial and it seems to not work when the highest element in the array is at position 0. Intuitively it didint make sense to me as to why we were taking right pointer as high as it was the pivot, so i tried changing r = high-1 which did not help at all and gave a partially sorted list back to me.
New contributor
Prabhanjana Ghuriki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.