A new start, with QuickSort Algorithm
Writing a blog is totally new for me. I would try to document my thoughts and ideas during learning or working (on projects mostly). At first it would be like a diary, just a note of what I have done recently. Hopefully, I can one day write down something more valuable and inspiring.
Today it is just the process of implementing QuickSort. Following is my code and I have commentted where I made a mistake.
#include <stdio.h> #include <stdlib.h> int ChoosePivot(int l, int r){ int randNum = rand(); int pivotIndex; pivotIndex = randNum %(r-l+1); pivotIndex = pivotIndex + l; return pivotIndex; } int PartitionAroundPivot(int* A, int pivotIndex, int l, int r){ int i,j; int pivot = A[pivotIndex], temp; i = l + 1; j = l; //swap pivot to the first one if (pivotIndex != l){ temp = A[l]; A[l] = A[pivotIndex]; A[pivotIndex] = temp; } for (j = l + 1; j < r + 1; j++){ if (A[j] < pivot) { temp = A[i]; A[i] = A[j]; A[j] = temp; i++; } } temp = A[i-1]; A[i-1] = pivot; A[l] = temp; //should swap A[i-1] instead of A[i]; return i-1; } void QuickSort(int* A, int l, int r){ int i; if (l<r){ int pivotIndex,pivotPos; pivotIndex = ChoosePivot(l,r); //return the index of the pivot pivotPos = PartitionAroundPivot(A,pivotIndex,l,r); for (i=0;i<6;i++){ printf("%d,",A[i]); } printf("\n"); QuickSort(A,l,pivotPos-1); QuickSort(A,pivotPos+1,r); } } int main(){ int A[6] = {5,1,5,3,5,6}; int i = 0; QuickSort(A,0,5); for (i = 0; i < 6; i++){ printf("%d,",A[i]); } printf("\n"); return 0; }
In a more detailed manner,
temp = A[i-1]; A[i-1] = pivot; A[l] = temp; //should swap A[i-1] instead of A[i];
This is the swapping step after partitioning the elements that are not pivot. At this point, i points to the first element that is larger than pivot. Therefore, we should swap the one left of it with the pivot. A rather foolish mistake.
Futhermore, I am not quite sure if rand() function in C generates random number uniformly in the range [0, RAND_MAX]. I have done some searching on Stack Overflow and Quora but have not yet understood the problem. Here are some urls that may help.
https://www.quora.com/The-rand-function-in-the-standard-C-library-returns-a-uniformly-random-number-in-0-RAND_MAX-1-Does-rand-mod-n-generate-a-number-uniformly-distributed-0-n-1
http://stackoverflow.com/questions/11641629/generating-a-uniform-distribution-of-integers-in-c