关闭

用结构体struct(数组)实现桶排序

266人阅读 评论(0) 收藏 举报
#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;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8101次
    • 积分:450
    • 等级:
    • 排名:千里之外
    • 原创:34篇
    • 转载:3篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论