Commonly used algorithms quick sort bucket sort...

Quick sort
ideas:
the default value is the most left baseline
to find the right from the reference value smaller than the value of the
find value greater than the reference value from the left
-exchange position (on the left is no major direct reference exchange position)
and so forth ...
as follows


    /**
     * 快速排序
     * @param a 排序数组
     * @param left 左下标
     * @param right 右下标
     */
    public void quickSort(int []a, int left, int right) {
        //右边游标小于等于左边游标排序结束
        if (right <= left) {
            return;
        }
        int tmp = a[left], 
            min = left, 
            max = right, 
            time;
        while (min < max) {
            //找到右边比左边小
            while (min < max && a[max] >= tmp) {
                max--;
            }
            //找到右边比左边大
            while (min < max && a[min] <= tmp) {
                min++;
            }
            //交换
            time = a[max];
            a[max] = a[min];
            a[min] = time;
        }
        //交换基准
        a[left] = a[min];
        a[min] = tmp;
        //对左边快排
        quickSort(a, left, max - 1);
        //对右边快排
        quickSort(a, max + 1, right);
    }

Bucket sorting
Key points:
take the data value as the array index, and the
array element records the number of occurrences of the data


```java
/**
     * 桶排序
     * @param a 排序数组
     */
    //桶排序
    public void buckSort(int a[]){
        //获取最大值
        OptionalInt max = Arrays.stream(a).max();
        //生成max+1个桶
        int[] bucks = new int[max.getAsInt() + 1];
        //记录每个数字的出现次数
        //索引为元素值,元素为值出现次数
        for (int i : a) {bucks[i]++;}
        //排序数组a的索引
        int index=0;
        //遍历桶,排序数组a重排序
        for (int i = 0; i < bucks.length; i++) {
            //根据数字出现次数(元素值),给排序数组赋值
            for (int j = 0; j < bucks[i]; j++) {
                a[index++]=i;
            }
        }
    }

Add more...

Guess you like

Origin blog.csdn.net/weixin_43158695/article/details/113611230