Radix Sort

Radix Sort - while(maxbit < 0) { unsigned mask =...

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

View Full Document Right Arrow Icon
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;
Background image of page 1

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

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: while(maxbit &lt; 0) { unsigned mask = (1 &lt;&lt; maxbit); if(mask &amp;&amp; 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&lt;b; i++) { int j=0; //array 2's index for(int k=0; k&lt;n; k++) { //copy entries that have 0 at array[i] if(array[k]&amp;(1&lt;&lt;i) == 0) { //array[k] has 0 at position i array2[j] = array[k]; j++; } } for(int k=0; k&lt;n; k++) { if((array[k]&amp;(1&lt;&lt;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

Page1 / 2

Radix Sort - while(maxbit &amp;amp;lt; 0) { unsigned mask =...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online