1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
// This function is simply the "interface" for the rest of the
// users code
void recursive_sort(char* arraytosort, int len)
{
// this is the starting call to the recursive function
qs(arraytosort, 0, len-1);
}
void qs(char* items, int left, int right)
{
int a, b;
a = left, b = right;
char x, y;
// this take the boundaries that were passed and then
// cuts the section in 2.
// But is this the numerical values of the first and
// last characters added together then divided by 2
// (Mean average)? Or is it the positional value of the
// elements?
x = items[(left+right)/2];
do
{
// 1) Is this "Keep incrementing the leftside pointer until
// we find a character that should be above halfway point"?
while((items[a] < x) && (a < b))
{
a++;
}
// 2) And then would this be "Decrement rightside pointer until we
// find a character that should be below the halfway point"?
while((x < items[b]) && (b > left))
{
b--;
}
// 3) therefore because these 2 characters are both on the wrong side
// of the halfway line simply swap them? Is that right?
// 4) But then what if B never found a suitable swapping character and
// just hit the x/mid point?
// Do we just swap anyway?
// and when it say "A <= B" is it referencing the positions of the pointers
// or the numerical values of the character they are pointing to?
if(a <= b)
{
y = items[a];
items[a] = items[b];
items[b] = y;
a++;
b--;
}
// This part I understand "Keep doing the above until the pointers meet"!
// 5) Except if B doesn't get reset, how can it carry on? Won't just stop
// at x/mid point again and have the same problem from my last question (Q4)?
}while(a <= b);
// 6) this will keep calling the function, each call reduces the
// partition in a leftward-direction fashion, continually swapping?
if(left < b) qs(items, left, b);
// 7) once the above recursion has been exhausted it does the same
// again, only this way going to the right, continually swapping?
if(a < right) qs(items, a, right);
}
|