This preview shows pages 1–2. Sign up to view the full content.

Radix Sort -a sorting algorithm that comsiders the structure of the keys -assumes tht the keys are stored in binary 5 – 101 1. Examine bits from right → left one column at a time 0 – 000 2 – 010 2. At every step, move entries with 0's in that column up 7 – 111 and entries with 1's down 3 – 011 Running Time of Radix Sort b → number bits of the key n → number of steps -steps + n moves/comparisons at every step = O(b*n) Implementation -use an array of unsigned ints using radix sort void radix(unsigned* array, int n) { /************************************** Input: “array” array of unsigned ints “n” number of elements in array Output: “array” sorted array ************************************* */ int b = sizeof(unsigned)*8; for(int i=0; i<n; i++) { x |=array[i]; } //determine position of leftmost bi int maxbit = sizeof(unsigned)*8 – 1;

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: while(maxbit < 0) { unsigned mask = (1 << maxbit); if(mask && x != 0) { //found a 1 break; } maxbit--; } int b = maxbit+1; //now perform radix sort unsigned int* array2 = new unsigned[n]; for(int i=0; i<b; i++) { int j=0; //array 2's index for(int k=0; k<n; k++) { //copy entries that have 0 at array[i] if(array[k]&(1<<i) == 0) { //array[k] has 0 at position i array2[j] = array[k]; j++; } } for(int k=0; k<n; k++) { if((array[k]&(1<<i)) != 0) { //array[k] has 1 at pos. i array2[j] = array[k]; j++; } } //copy array2 memcpy(array, array2, n*sizeof(unsigned)); } //end for loop with I delete array2; } //end radix-radix sort is better than other algorithms only if b is small Ex: b=3 n=1024 → O(b*n) O(3*1024) → better than O(n log(n))...
View Full Document

{[ snackBarMessage ]}