Bucket sorting + sorting stability and summary

Bucket sorting

Sorting based on bucket sorting: counting sorting & cardinal sorting

1) The sorting under the bucket sorting idea is not based on comparison

2) The time complexity is O(N), and the additional space load is O(M)

3) The application scope is limited, and the data status of the sample needs to meet the division of barrels

1) Generally speaking, the counting sorting requires that the sample is an integer and the range is relatively narrow (employee age)
2) Generally speaking, the cardinality sorting requires that the sample is a positive integer in hexadecimal
Once a slight upgrade is required, the increased cost of rewriting is obvious

Count sort

/**
 * Count sort
 */
public class CountSort {

    //Sort employees by age
    public static void sort(int[] ages){
        if(ages ==null || ages.length < 2){
            return;
        }
        //1. Find out the maximum age
        int maxAge = Integer.MIN_VALUE;
        for (int age : ages) {
            maxAge = Math.max(maxAge,age);
        }
        //Auxiliary array
        int[] help = new int[maxAge + 1];
        for (int i = 0; i < ages.length; i++) {
            help[ages[i]]++;
        }
        //Traverse the auxiliary array and put the array into ages
        int i = 0;
        for (int j = 0; j < help.length; j++) {
            while (help[i]-- >0){
                ages[i++] = j;
            }
        }

    }
}

Cardinality sort

package com.lzf2.class07;

import java.util.Arrays;

/**
 * Cardinality sort
 */
public class RadixSort {
    // only for no-negative value
    public static void radixSort(int[] arr){
        if(arr==null || arr.length < 2){
            return;
        }
        radixSort(arr,0,arr.length - 1,maxbits(arr));
    }
    //How many digits is the maximum number
    public static int maxbits(int[] arr){
        int max = Integer.MIN_VALUE;
        for (int i : arr) {
             max = Math.max(max,i);
        }
        int res = 0;
        while (max != 0){
            res++;
            max /= 10;
        }
        return res;
    }
    public static int getDigit(int x, int d) {
        return ((x / ((int) Math.pow(10, d - 1))) % 10);
    }
    // arr[L..R] sort, decimal digit of the maximum value
    public static void radixSort(int[] arr, int L, int R, int digit) {
        int radix = 10;//base
        int[] help = new int[R - L + 1];
        for (int d = 1; d <= digit; d++) {//You can go in and out as many times as you have

            int[] count = new int[radix];//Count the number of each number in this bit
            for (int i = L; i <= R; i++) {
                int num = getDigit(arr[i],d);
                count[num]++;
            }
            //Change count to cumulative sum
            for (int i = 1; i < radix; i++) {
                count[i] = count[i] + count[i - 1];
            }
            //Traverse the original array from left to right and adjust the position
            for (int i = R; i >= L; i--) {
                int num = getDigit(arr[i],d);
                help[count[num] - 1] = arr[i];
                count[num]--;
            }
            //The auxiliary array is copied back to the original array
            for (int i = L,j = 0; i <= R; i++,j++) {
                arr[i] = help[j];
            }
        }


    }


    // for test
    public static void comparator(int[] arr) {
        Arrays.sort(arr);
    }

    // for test
    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random());
        }
        return arr;
    }

    // for test
    public static int[] copyArray(int[] arr) {
        if (arr == null) {
            return null;
        }
        int[] res = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            res[i] = arr[i];
        }
        return res;
    }

    // for test
    public static boolean isEqual(int[] arr1, int[] arr2) {
        if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
            return false;
        }
        if (arr1 == null && arr2 == null) {
            return true;
        }
        if (arr1.length != arr2.length) {
            return false;
        }
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
        return true;
    }

    // for test
    public static void printArray(int[] arr) {
        if (arr == null) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    // for test
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100000;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generateRandomArray(maxSize, maxValue);
            int[] arr2 = copyArray(arr1);
            radixSort(arr1);
            comparator(arr2);
            if (!isEqual(arr1, arr2)) {
                succeed = false;
                printArray(arr1);
                printArray(arr2);
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");

        int[] arr = generateRandomArray(maxSize, maxValue);
        printArray(arr);
        radixSort(arr);
        printArray(arr);

    }
}

Stability of sorting

Stability means that the relative order of samples of the same size will not change after reordering

Stability is meaningless for the foundation type

Stability is important for non basic types

Some sorting algorithms can be stable, while some sorting algorithms can not be stable anyway

Sort summary

1) It is not based on comparison and has strict requirements on sample data, which is not easy to rewrite
2) Sorting based on comparison can be reused directly as long as the size ratio of two samples is specified
3) Based on comparison sorting, the limit of time complexity is O(NlogN)
4) The time complexity O(NlogN), the additional space complexity is lower than O(N), and the stable comparison based sorting does not exist.
5) Select fast row for absolute speed, stack row for space saving, and merge for stability

Common pit

1) The additional space complexity of merge sort can become O(1), "merge sort internal cache method", but it will no longer be stable.

2) "Merge and sort in place" is a garbage post, which will turn the time complexity into O(N^2)

3) The stability of quick sort is improved, "01 stable sort", but it will require more sample data.

In an integer array, please put odd numbers on the left and even numbers on the right of the array. The original relative order between all odd numbers and all even numbers shall remain unchanged. The time complexity shall be O(N) and the additional space complexity shall be O(1).

can't meet the requirements

1) The additional space complexity of merge sort can become O(1), "merge sort internal cache method", but it will no longer be stable.

2) "Merge and sort in place" is a garbage post, which will turn the time complexity into O(N^2)

3) The stability of quick sort is improved, "01 stable sort", but it will require more sample data.

In an integer array, please put odd numbers on the left and even numbers on the right of the array. The original relative order between all odd numbers and all even numbers shall remain unchanged. The time complexity shall be O(N) and the additional space complexity shall be O(1).

can't meet the requirements

Tags: Java Algorithm

Posted on Tue, 12 Oct 2021 03:05:02 -0400 by upit