{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

notes36

# notes36 - if n is very large m is very small compared to n...

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

cs 251 Bucket Sort -sorting algorithm that works for limited range of numbers -create array of counters, or buckets, that are incremented when the array is scanned -the counters give a histogram of the occurence of the numbers -this histogram also gives information about the sorted sequence Example: | represents a tally ====== array: 2, 1, 3, 1, 2 buckets: subrange 1...3 1: || 2: || 3: | -once the histogram is built, print as many of occurences of each number as they appear 1, 1, 2, 2, 3 complexity: ======== m = number of different numbers n = number of elements 1. scan array to build histogram ==> O(n) 2. print numbers ==> scan buckets + print keys ==> O(m) + O(n) so, total time = O( n + m ) -Bucketsort is a very good sorting algorithm

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: if: n is very large m is very small compared to n Implementation void bucketSort( int *a, int n ) { //search for the range int min = a[0]; int max = a[0]; for (int i = 0; i < n; i++) { if (min > a[i]) { min = a[i]; } if (max < a[i]) { max = a[i]; } } int m = max - min + 1; //range //create buckets int *buckets = new int[ m ]; //initialize buckets with 0s memset( buckets, m * sizeof(int), 0 ); //create histogram for (int i = 0; i < n; i++) { buckets[ a[i] - min ]++; } //put histogram back into array for (int i = 0, int j = 0; j < m; j++) { for (int k = 0; k < buckets[j]; k++) { a[i] = j + min; i++ } } } //end of bucket sort...
View Full Document

{[ snackBarMessage ]}