70 likes | 225 Views
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++ )
E N D
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() } } }
0 1 2 3 4 5 6 7 8 9 Bins: 0 1 2 3 4 5 6 7 8 9 Simple Binsort 8 5 6 0 3 9 2 4 1 7 A[]: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 for( int i = 0; i < n; i++ ) { a[i].key = bin[i] } for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key }
0 3 5 6 9 Bins: 0 1 2 3 4 5 6 7 8 9 Simple Binsort (another example) 9 5 6 0 3 A[]: 0 1 2 3 4 0 3 5 6 9 for( int i = 0, j=0; i < n; i++ ) { if( bin[i].isNotEmpty() ) { a[j].key = bin[i] j++ } } for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key }
5 8 5 6 8 45 6 39 8 42 39 39 42 5 42 45 45 6 75 75 75 91 97 91 95 97 95 91 97 95 8 8 5 6 8 8 5 6 8 5 6 8 6 6 6 39 0 0 39 39 0 3 42 45 42 45 45 42 3 3 9 9 9 2 2 2 4 4 75 75 75 4 1 1 1 7 91 95 97 97 91 95 7 91 95 97 7 buckets: 0 1 2 3 4 5 6 7 8 9 BucketSort (buckets by 10’s) Keys: 0 4 3 4 0 0 7 9 9 9 A[]: for each Bucket { sort the elements in it. } for each element in A[] { put the element in its proper bucket B[a[].key] } 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 } }
5 91 8 5 6 45 6 42 8 45 39 8 5 39 42 39 75 42 42 5 45 45 95 6 75 75 75 6 91 97 97 91 8 95 95 91 97 95 97 39 Sorted: 2nd Pass: 1st Pass: Original: Radixsort: Illustration Sort the numbers according to the ones place. Sort the numbers according to the tens place.