I have a hard time translating QuickSort with Hoare partitioning into C code, and can\'t find out why. The code I\'m using is shown below:
void QuickSort(in
First of all u misunderstood the Hoare's partition algorithm,which can be see from the translated code in c, Since u considered pivot as leftmost element of subarray.
Ill explain u considering the leftmost element as pivot.
int HoarePartition (int a[],int p, int r)
Here p and r represents the lower and upper bound of array which can be part of a larger array also(subarray) to be partitioned.
so we start with the pointers(marker) initially pointing to before and after end points of array(simply bcoz using do while loop).Therefore,
i=p-1,
j=r+1; //here u made mistake
Now as per partitioning we want every element to the left of pivot to be less than or equal to pivot and greater than on right side of pivot.
So we will move 'i' marker untill we get element which is greaterthan or equal to pivot. And similarly 'j' marker untill we find element less than or equal to pivot.
Now if i < j we swap the elements bcoz both the elements are in wrong part of array. So code will be
do j--; while (a[j] <= x); //look at inequality sign
do i++; while (a[i] >= x);
if (i < j)
swap(&a[i],&a[j]);
Now if 'i' is not less than 'j',that means now there is no element in between to swap so we return 'j' position.
So now the array after partitioned lower half is from 'start to j'
upper half is from 'j+1 to end'
so code will look like
void QuickSort(int a[],int start,int end) {
int q=HoarePartition(a,start,end);
if (end<=start) return;
QuickSort(a,start,q);
QuickSort(a,q+1,end);
}