看千遍知識,不如寫百行**。
開始我的fb之旅。
從最簡單的排序開始。寫一下桶排序方法。
輸入:一堆待排序的數字(10,23,43,54,323…)
輸出:排序好的結果
首先簡單解釋一下什麼叫桶排序。首先列出乙個陣列a[m],我們把這個陣列比作大小為m的桶組合, 每個陣列元素象徵了乙個桶。假設待排序的數字總數為n個,將這n個數字丟到m個桶裡,丟放規則可以自定,比如可以利用取餘法,如針對具體某個數字n,做取餘s=n%m,則將該數字n有序的放到第s個桶裡。這裡放入後會出現兩種情況,第一種情況:當桶足夠大,待排序陣列足夠小的話,待排序的陣列可以放入互不重疊的桶裡,每個桶裡只有乙個待排序陣列的數字或者沒有被放入數字。第二種,就是有多餘2個數字被丟入了同乙個桶裡,這裡需要做的是,保證每個桶裡的數字是有序的。放好後會得到m個有序排列的桶,接下來就需要通過融合,將這m個有序排列的子陣列合併成乙個長的陣列,從而得到排序結果。
所以說事實上,桶排序只是通過增加額外的空間,來進行排序的目的,平均複雜度可以達到o(n)。
實現**如下:
bucketsort.h
bucketsort.cpp#include
const
int bucketnum = 4;
struct listnode
listnode* mnext;
};class bucketssort
;
main 函式#include "buctetsort.h"
#include bucketssort::bucketssort():buckets()
}bucketssort::~bucketssort()
}void bucketssort::bucket_sort(int n, int
array) else
listnode *tmp = new listnode(array[i]);
p->mnext = tmp;
tmp->mnext = q;}}
listnode* head = buckets[0]->mnext;
for (int i = 1;i < bucketnum;i++)
listnode *p = head;
for (int i = 0;i < n;i++)
while (p != null)
}listnode* bucketssort::merge(listnode *head1, listnode*head2)
else
head = head->mnext;
}if (head1 == null)head->mnext = head2;
if (head2 == null) head->mnext = head1;
return p->mnext;
}
#include "buctetsort.h"
#include
using
namespace
std;
void print(int n,int
array)
cout
<< endl;
}int main()
h->bucket_sort(num , array);
delete
array;
delete h;
return
0;}
排序演算法之桶排序
1 設定乙個定量的陣列當作空桶子 2 尋訪序列,並且按照要求把記錄乙個乙個放到對應的桶子去 3 對每個不是空的桶子進行排序。4 從不是空的桶子裡把專案再放回原來的序列中。include include include include typedef struct node node,list voi...
排序演算法之桶排序
桶排序 bucket sort 或所謂的箱排序,是乙個排序演算法,工作的原理是將陣列分到有限數量的桶子裡。每個桶子再個別排序 有可能再使用別的排序演算法或是以遞迴方式繼續使用桶排序進行排序 根據最大值最小值建立多個桶,確定各個桶之間的跨度,然後遍歷原始數列,把各元素放到對應的桶中,先是每個桶內的元素...
排序演算法之桶排序
桶排序 bucket sort 或所謂的箱排序,是乙個排序演算法,工作的原理是將陣列分到有限數量的桶子裡。每個桶子再個別排序 有可能再使用別的排序演算法或是以遞迴方式繼續使用桶排序進行排序 桶排序是鴿巢排序的一種歸納結果。當要被排序的陣列內的數值是均勻分配的時候,桶排序使用線性時間 n 但桶排序並不...