桶排序 java版

又一線性時間的排序算法。對於線性排序算法的思考,可以看看編程珠璣第一章的內容,研究算法問題的時候要仔細分析好,看清楚問題的數據的結構和分佈情況,桶排序要求輸入服從均勻分佈才發揮其性能

代碼:

package com.xingzhe.bucketsort;
import java.util.ArrayList;
/**
 * 桶排序,要求輸入的數據都服從均勻分佈 算法假設每個元素a[i]滿足 0<=a[i]<1
 *
 * @author Hercules
 *
 */
public class BucketSort {
    public static void bucket_sort(double[] a) {
        // 獲取長度
        int length = a.length;
        // 此處需要建立一個長度爲length的臨時數組,每個數組中存放鏈表,由於java沒有泛型數組,故用ArrayList來代替
        ArrayList<ArrayList<Double>> b = new ArrayList<ArrayList<Double>>();
        // 把“數組”的每個元素都初始化爲空鏈表
        for (int i = 0; i < a.length; i++) {
            b.add(new ArrayList<Double>());
        }
        // 把待排序的數組中的每個元素插入到臨時數組中
        for (int i = 0; i < a.length; i++) {
            b.get((int) Math.floor(length * a[i])).add(a[i]);
        }
        // 對每個鏈表進行插入排序
        for (int i = 0; i < a.length; i++) {
            insert_sort(b.get(i));
        }
        // 把臨時數組中的每個鏈表的值取出來合併
        int ai = 0;
        for (int i = 0; i < b.size(); i++) {
            if (b.get(i).size() == 0) {
                continue;
            }
            for (int j = 0; j < b.get(i).size(); j++) {
                a[ai++] = b.get(i).get(j);
            }
        }
    }
    /*
     * 針對鏈表的插入
     */
    private static void insert_sort(ArrayList<Double> array) {
        if (array.size() == 0)
            return;
        for (int j = 1; j < array.size(); j++) {
            double key = array.get(j);
            int i = j - 1;
            while (i >= 0 && array.get(i) > key) {
                array.set(i + 1, array.get(i));
                i--;
            }
            array.set(i + 1, key);
        }
    }
    public static void main(String[] args) {
        double[] a = new double[] { 0.25, 0.36, 0.25, 0.65, 0.18, 0.48, 0.27,
                0.29, 0.24, 0.75 };
        bucket_sort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}


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