Radix Sort CSC 172 SPRING 2004 LECTURE 25
Theoretical bound? A * n logn = t A* 524,288 * 19 = 111 A = 1.1*10^-5 1.1*10^-5 * 134,217,728 * 27 = 40, *10^-5 * 524,288 * 256 * 27/19 = 40,380 But we got ~26,700 ~= 111 * 256
What happened? The key word in the theoretical proof was “comparison based” Some sorts are not comparison based
Radix Sort Unlike other methods, radix sort considers the structure of the keys Assume that the keys are represented in base M number system (M == radix) i.e. if M == 2 we are in the binary number system 9 10 == Sorting is done by comparing bits in the same position This will extend to keys that are alphanumeric strings
Radix Exchange Sort Sort array with respect to the leftmost bit
Radix Exchange Sort Partition Array Recursively sort subarrays Ignoring leftmost bit
Time How many bits in the keys? “b” How much work per bit? “N” O(bN) Not bad for 16 bit shorts
Exchange In place, like Quicksort Repeat Scan top-down to find a “1” Scan bottom-up to find a “0” Exchange keys Until scan indices cross
public static void mySorter(short[]B) { int mask = 0x8000; mySorter(B,0,B.length -1, mask); }
public static void mySorter(short[] B,int bottom,int top, int mask){ if (mask <= 0 ) return; int oldtop = top; int oldbottom = bottom; while (top > bottom) { while ((bottom < (B.length - 1)) && ((((int) B[bottom]) & mask) == 0)) bottom++; while ((top >0) && ((((int) B[top]) & mask) > 0)) top --; if (top > bottom) { short temp = B[bottom]; B[bottom] = B[top]; B[top] = temp; } mySorter(B,oldbottom,top,mask>>1); mySorter(B,top+1,oldtop,mask>>1); return; }