BucketSort

# BucketSort - for(int i=0 i<n i if(min> array[i min =...

This preview shows page 1. Sign up to view the full content.

Bucket Sort -a sorting algorithm where the elements in the array have their own range of elements sort → array={2, 1, 3, 2, 2, 2, 1} -create an array of counters of 3 elements //m = range of values 1 → II \ 2 → IV | → O(n) //m = size of range 3 → I / -go over the counters and store in the arry the number of occurances of each value {1, 1, 2, 2, 2, 2, 3} ← O(m) + O(n) =O(m+n) Bucket Sort Implementation void bucketSort(unsigned* array, int n) { unsigned min = array[0]; unsigned min = array[0];
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for(int i=0; i<n; i++) { if(min > array[i]) min = array[i]; if(max < array[i]) max = array[i]; int m = max-min+1; unsigned* bucket = new unsigned[m]; } for(i=0; i<n; i++) { bucket[array[i]-min]++; } // put 3elements back into array int i=0; for(int k=0; k<m; k++) { for(int l=0; l<bucket[k]; l++) { array[i]=k+min i++; } } delete bucket; //delete bucket array } //end bucketSort O(m+n) → bucket sort is faster than other algorithms O(n log(n) as long as m is small...
View Full Document

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

Ask a homework question - tutors are online