O(n) Algorithms
Binsort/Bucketsort: Algorithm /* Put a range of values in bins and then sort the contents of each bin and then output the values of each bin in order. */ void binsort( Elem[] a, int n ) { List[] B = new List[ MAX_KEY_VALUE ] for( i=0; i<n; i++ ) B[ a[i].key ].append( a[i] ) int index = 0 for( i=0; i< MAX_KEY_VALUE; i++) {for( B[i].first(); B[i].isInList(); B[i].next() ) {a[i] = B[i].currentValue() }
Simple Binsort Bins: for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key } for( int i = 0; i < n; i++ ) { a[i].key = bin[i] } A[]:
Simple Binsort (another example) Bins: for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key } for( int i = 0, j=0; i < n; i++ ) {if( bin[i].isNotEmpty() ) {a[j].key = bin[i] j++ } A[]:
BucketSort (buckets by 10’s) buckets: Keys: for each element in A[] {put the element in its proper bucket B[a[].key] } A[]: for each Bucket {sort the elements in it. } for each Bucket {copy the elements back into the original array }
Radixsort: Algorithm void radixsort( Elem[] a, Elem[] B, int n, int k, int r, Elem[] count) {// count[i] stores the number of records in bin[i] for( int i=0, rtok=1; i<k; i++, rtok*=r) //for k digits {for( int j=0; j<r; j++) count[j]=0; //initialize count //Count the no. of records for each bin on this pass for( j=0; j<n; j++ ) count[ (a[j].key / rtok) % r ] ++ // Index B: count [j] will be index for last slot of bin j for( j=1; j<r; j++ ) count[j] = count[j-1] + count[j] // put records into bins working from bottom of each bin // since bins fill from the bottom, j counts downwards for( j=n-1; j>=0; j--) B[--count[ (a[j].key / rtok) % r ] ] = a[j] for( j=0; j<n; j++ ) a[j] = B[j] //copy B back into a }
Radixsort: Illustration Original: st Pass: nd Pass: Sort the numbers according to the ones place.Sort the numbers according to the tens place Sorted: