Radix Sort

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

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 < 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

This note was uploaded on 02/04/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 2

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

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