Download presentation
Presentation is loading. Please wait.
Published byKristina Douglas Modified over 9 years ago
1
O(n) Algorithms
2
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() }
3
Simple Binsort 5603924178 2345678901 2345678901 Bins: for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key } 1234567890 for( int i = 0; i < n; i++ ) { a[i].key = bin[i] } 1234567890 A[]:
4
Simple Binsort (another example) 56039 23401 2345678901 Bins: for( int i = 0; i < n; i++ ) { bin[ a[i].key ] = a[i].key } 35690 for( int i = 0, j=0; i < n; i++ ) {if( bin[i].isNotEmpty() ) {a[j].key = bin[i] j++ } 35690 A[]:
5
BucketSort (buckets by 10’s) 45394256759791958 2345678901 603924178 buckets: 603924178 39 45 4275 97 91 95 856856 Keys: 3400799904 for each element in A[] {put the element in its proper bucket B[a[].key] } A[]: for each Bucket {sort the elements in it. } 603924178 39 42 4575 91 95 97 568568 for each Bucket {copy the elements back into the original array } 568568 5 6 8 39 42 45 42 45 75 91 95 97 91 95 9768394245759195975
6
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 }
7
Radixsort: Illustration 45394256759791958 Original: 4242 45455 7575 95956 97978 3939 9191 1 st Pass: 68 3939 4242 4545 7575 9191 9595 9797 5 2 nd Pass: Sort the numbers according to the ones place.Sort the numbers according to the tens place. 68394245759195975 Sorted:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.