排序演算法:基數排序(桶排序)

來源:互聯網
上載者:User
簡介

基數排序(升序)是一種非比較式的排序方式,和之前博文中提到的快排,冒泡排序,插入排序這些排序演算法不一樣,它沒有使用任何交換的方式,那麼又是通過什麼方式進行的排序呢。它的基本思想是通過分配的方法把元素從小到大分配,以到達排序的作用。 演算法描述

1.建立10個桶,分別用來放對應的數字;
2.按照最低位(個位)的數字分配到相應的桶裡面;
3.把桶裡的數字依次放回數組;
4.按照次低位的數字分配到相應的桶裡面;
5.把桶裡的數字依次放回數組;
6.重複上面工作直到每個數位每個位都被訪問到。 時間複雜度:

桶排序是一種十分高效的排序演算法,時間複雜度為O(N),很多時候比快排還要快,而且桶排序十分穩定,唯一的缺點是他的空間複雜度高於其他幾種排序。 如圖

對個位分配

對十位分配

對百位分配
代碼實現

#include<iostream>#include<list>using namespace std;int GetMax(int* arr, int size){//計算最大位元    int n = 1;    int base = 10;    for (int i = 0; i < size; ++i)    {        while (arr[i] >= base)        {            n++;            base *= 10;        }    }    return n;}void BucketSort(list<int>* l,int* a, int size){    int i = 0;    int index = 0;    int n = GetMax(a, size);    int x = 1;    while (n--)    {        for (i = 0; i < size; ++i)        {//分配到桶中            index = a[i]/x % 10;            l[index].push_back(a[i]);        }        int j = 0;        int k = 0;        for (j = 0; j < 10; ++j)        {//放回數組            while (!l[j].empty())            {                a[k++] = l[j].front();                l[j].pop_front();            }        }        x *= 10;    }}int main(){    list<int> l[10];//使用了list數組來充當桶的作用    int a[10] = { 12,45,13,65,85,111,23,15,17,56 };    int len = sizeof(a) / sizeof(a[0]);    BucketSort(l, a, len);    for (int i = 0; i < len; i++)    {        cout << a[i] << " ";    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.