Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. (Wikipedia)
Worst case performance - O(n^2)
Javavoid bucket_sort(int array[], int length)
{
int k = max_value(array,length);
int bucket[k+1];
for(int i=0; i<=k; i++)
{
bucket[i] = 0;
}
for(int j=0; j<length; j++)
{
bucket[array[j]]++;
}
int index = 0;
for (int i=0; i<=k; i++)
{
for (int j=0; j<bucket[i]; j++)
{
array[index++]=i;
}
}
}
int max_value(int array[], int length)
{
int max = 0;
for (int i = 0; i < length; i++)
if (max < array[i])
max = array[i];
return max;
}
Matlabpublic int[] bucket_sort(int[] array) {
int k = max_value(array);
int[] bucket = new int[k+1];
for (int j = 0; j < array.length; j++) {
bucket[array[j]]++;
}
int index = 0;
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
array[index++] = i;
}
}
return array;
}
public int max_value(int[] array) {
int max = 0;
for (int i = 0; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
}
}
return max;
}
Pythonfunction array = bucket_sort(array)
k = max(array);
bucket = zeros(1,k+1);
B = zeros(1,numel(array));
for j = 1:numel(array)
bucket(array(j)) = bucket(array(j)) + 1;
end
index = 1;
for i = 1:k+1
for j = 1:bucket(i)
array(index) = i;
index = index + 1;
end
end
end
def bucket_sort(array):
k = max(array)
bucket = [0]* (k+1)
for j in range(len(array)):
bucket[array[j]] = bucket[array[j]] + 1
index = 0
for i in range(k+1):
for j in range(bucket[i]):
array[index] = i
index = index + 1
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteDoes any1 have this code in Julia?
ReplyDeleteExploring in Yahoo I at last stumbled upon this website. Barkatullah University BA Part 3rd Result
ReplyDelete