# 用结构体struct（数组）实现桶排序

#include <iostream>
#include "hello.h"
#include "list"
#include "console.h"
#include "random"
#include "time.h"
#include "string.h"
using namespace std;

typedef struct{
int node[10];
int count;
}*pBarrel, Barrel;

void print(int arr[], int n){
for(int i = 0; i < n; i++)
cout<<arr[i]<<"  ";
cout<<endl;
}

void sort(int A[], int p, int q){
for(int i = p; i < q; i++){
int j = i;
int key = A[i+1];
while(A[j]>key && j>=p){
A[j+1] = A[j];
j--;
}
A[j+1] = key;
}
}

void barrel_sort(int A[], int n){
int max = 0, min = 0;
for(int i = 0; i < n; i++){
if(A[i] > max)
max = A[i];
else if(A[i] < min)
min = A[i];
}
int num = max-min+1;
int count_of_A = 0;
pBarrel ptr;
ptr = (pBarrel)malloc(sizeof(Barrel)*10);
memset(ptr, 0, sizeof(Barrel)*10);
for(int i = 0; i < n; i++){
int index = ((A[i]-min)*10)/num;
(ptr+index)->node[((ptr+index)->count)] = A[i];
(ptr+index)->count++;
}
for(int i = 0; i < 10; i++){
sort((ptr+i)->node, 0, (ptr+i)->count -1); //注意边界
for(int j = 0; j < (ptr+i)->count; j++)
A[count_of_A++] = (ptr+i)->node[j];
}

}

int main() {
int A[30];

srand(time(NULL));
for(int i = 0; i < 30; i++)
A[i] = rand()%100;
print(A,30);
cout<<endl<<"now:"<<endl;
barrel_sort(A, 30);
print(A, 30);
return 0;
}



• 本文已收录于以下专栏：

举报原因： 您举报文章：用结构体struct（数组）实现桶排序 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)