#include "sort_.h"
void print_array(int *arr, int n)
// 打印数组
{
if(n==0){
printf("ERROR: Array length is ZERO\n");
return;
}
printf("%d", arr[0]);
for (int i=1; i<n; i++) {
printf(" %d", arr[i]);
}
printf("\n");
}
int* sort_array(int *arr, int n)
// 函数参数:乱序整数数组 数组长度
// 函数返回值:返回从小到大排序后的数组
{
int max = *max_element(arr,arr+n);
int min = *min_element(arr,arr+n);
int bucketNum = (max-min)/n + 1;
int *bucket = new int[bucketNum*n];
int *bucketIndex = new int[bucketNum];
fill(bucketIndex,bucketIndex+bucketNum,-1);
for(int i=0;i<n;i++){
int index = arr[i]/(n+1);
bucketIndex[index]++;
bucket[index*n+bucketIndex[index]] = arr[i];
}
for(int i=0;i<bucketNum;i++){
if(bucketIndex[i]!= -1){
sort(bucket+i*n,bucket +i*n +bucketIndex[i]+1);
}
}
int index = 0;
for(int i=0;i<bucketNum;i++){
int a = 0;
while(bucketIndex[i]>=0){
arr[index] = bucket[i*n + a];
a++;
index++;
bucketIndex[i]--;
}
}
return arr;
}
C语言实现桶排序
最新推荐文章于 2024-06-28 15:08:54 发布