The topics covered in this lecture include a buggy Quick Sort routine and a test case. Though, there are some more bugs in the routine which we discussed in lecture9 like typecasting from int to unsigned int. Try to find them yourself.
Strategy:
<= mid |
>mid |
void sort(int *array, u_int nelt, int (*fn) (int, int))
{
int mid, smallix, bigix ;
if (nelt <= 1) return;
mid = array[0];
smallix = 0;
bigix = nelt;
while ( smallix < bigix )
{
while ( smallix < nelt && array[smallix] <= mid )
smallix++;
while ( bigix >=0 && array[bigix - 1] > mid )
bigix--;
t = array[smallix];
array[smallix] = array[bigix];
array[bigix - 1] = t;
}
sort(array, smallix);
sort(array + smallix, nelt - smallix);
}
Lets, suppose we call the sort routine with:
nelt = 3
array[0] = 3
array[1] = 2
array[2] = 1
sort (int * array, 3)
The values of some variables at different points of execution:
mid = 3
smallix = 1-> 2 ->3
bigix = 3
.
.
.
.
Now, we are going to make a recursive call to the sort routine
sort ( array, smallix); // smallix = 3
sort(int * array, 3)
OOPS! This routine never really terminates and the array also remains
the same. Testing the program with different inputs can help us find out
the bugs.
Another strategy that we could apply on the quick sort routine :
Strategy:
< mid |
>= mid |
We will talk more about this in the upcoming lectures.