淺談排序算法之計數排序(7)

接下來的三篇博客裏,筆者將會簡單聊聊三種線性時間複雜度的排序算法,即計數排序、基數排序以及桶排序,均出自《算法導論》。
計數排序(counting sort)假設數組A中的所有元素都是0~k區間內的一個整數,其中k爲某個整數值。計數排序的思想是對每一個數組元素x,計算小於x的元素的個數。計數排序的實現過程分爲三步:

  1. 計算數組A中每個元素出現的次數。
  2. 統計數組A中存在多少個元素小於等於A中的指定元素。
  3. 從後往前依次遍歷數組A,將每個元素放置在輸出數組中正確的位置上。

示例代碼如下:

package org.vimist.pro.Algorithm.Sort;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Random;

/**
 * An illustration of {@code CountingSort}.
 *
 * @author Mr.K
 */
public class CountingSort {

    /**
     * length of array to be sorted
     */
    private static int N = 20;

    /**
     * upper bound for element in array
     */
    private static int UpperBound = 2 * N;

    public static void main(String[] args) {
        int[] arr = new int[N];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(UpperBound);
        }
        System.out.println("待排序數組: " + Arrays.toString(arr));
        int[] ans = Counting_Sort(arr);
        System.out.println("已排序數組: " + Arrays.toString(ans));
    }

    /**
     * Accepts an array to be sorted and returns a sorted array. In this method,
     * two integer arrays should be established. One of which is a counting array,
     * the other one is an array to be returned. This method comprises three loops.
     * <ul>
     *     <li>The first <em>For-Loop</em> is to figure out the times of each unique
     *     element in the specified array.</li>
     *     <li>The second <em>For-Loop</em> works on the counting array, in the
     *     range from 1 to length - 1, where current element changes to the value
     *     of summation of current element and previous element.</li>
     *     <li>The third <em>For-Loop</em> works also on the specified array. For
     *     each current element in specified array, find how many elements is less
     *     current element, which means the end index of current element in specified
     *     array. And then assign the result array using the end index with current
     *     element.</li>
     * </ul>
     * This method is stable, obviously. And operations are linear. The total cost
     * of time for this method is theta(k + n), where k is the upper bound of elements
     * of specified array. In general, the complexity of time is theta(n). In this
     * sort, there exists some assumptions that each element in the specified array
     * locates in the range [0, k].
     *
     * @param arr specified array to be sorted
     * @return a sorted array
     */
    public static int[] Counting_Sort(@NotNull int[] arr) {
        int[] counts = new int[UpperBound + 1], ans = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            counts[arr[i]]++;
        }
        for (int i = 1; i < counts.length; i++) {
            counts[i] = counts[i] + counts[i - 1];
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            ans[counts[arr[i]]-- - 1] = arr[i];
        }
        return ans;
    }

}

運行結果如下:

待排序數組: [27, 3, 7, 21, 5, 22, 1, 3, 33, 9, 36, 17, 26, 39, 39, 9, 22, 21, 30, 13]
已排序數組: [1, 3, 3, 5, 7, 9, 9, 13, 17, 21, 21, 22, 22, 26, 27, 30, 33, 36, 39, 39]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章