notes36

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

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

View Full Document Right Arrow Icon
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
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: 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

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

Page1 / 2

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

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