borderLands

step by step

用结构体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;
}


阅读更多
上一篇c++链表std::list
下一篇c++11版本list中sort用lambda表达式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭