桶排序

来源:互联网 发布:免费健身软件 编辑:程序博客网 时间:2024/04/28 16:22
#include <iostream>using namespace std;class listnode{public:int elem;listnode* next;listnode(){next = 0;}};class list{public:listnode* head;list(){head = NULL;}~list(){listnode* t = head;while (t != 0){listnode* tmp = t;t = t->next;delete tmp;}}void insertElem(int elem){listnode* node = new listnode();node->elem = elem;node->next = 0;if (head == NULL){head = node;}else{if (node->elem < head->elem){node->next = head;head = node;}else{listnode* prev = head;listnode* t = head->next;while (t != 0){if (node->elem < t->elem){prev->next = node;node->next = t;return ;}prev = t;t = t->next;}prev->next = node;}}}void print_list(){listnode* t = head;while (t){cout << t->elem << " ";t = t->next;}cout << endl;}};void print_array(int* array, int size){for (int i=0; i<size;  i++)cout << array[i] << " ";cout << endl;}void bucket_sort(int* array, int size){list* buckets = new list[10]; //假设分成10个区间for (int i=0; i<10; i++)buckets[i].head = NULL;for (int i=0; i<size; i++){int which_bucket = array[i] / 100;buckets[which_bucket].insertElem(array[i]);}int m = 0;for (int i=0; i<10; i++){// copy backlistnode* t = buckets[i].head;while (t != 0){array[m] = t->elem;t = t->next;m++;}}delete[] buckets;}void main(){int* array = 0;int size;cout << "input the size:";cin >> size;array = new int[size];for (int i=0; i<size; i++){array[i] = rand()%1000;}print_array(array, size);bucket_sort(array, size);print_array(array, size);}