線性時間排序--桶排

1、桶排序

  可以排序的範圍數較小,是一種以空間換時間的排序算法;

  不考慮重複元素的出現---->桶排;解決方案在計數排序;

  (1)、代碼實現

#include<stdio.h>

void bucketSort(int *a, int count);
void showArray(int *a, int count);

void showArray(int *a, int count){
    int i;

    for(i = 0; i < count; i++){
        printf("%d ", a[i]);
    }
    printf("\n");
}

void bucketSort(int *a, int count){
    int b[10] = {0};  //知道要排序值的最大範圍
    int i;
    int n = 0;

    for(i = 0; i < count; i++){
        b[a[i]]++;
    }

    for(i = 0; i < 10; i++){
        if(b[i]){
            a[n++] = i;
        }
    }
}

void main(void){
    int a[] = {3, 5, 1, 8, 9, 6};
    int count = sizeof(a)/sizeof(int);

    bucketSort(a, count);
    showArray(a, count);
}

  (2)、結果截圖

wKiom1in2jGw4B6GAAATehBikxo765.png-wh_50

  (3)、算法分析

  時間複雜度:O(n);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章