9 basic sorting algorithms

Sorting Categories Overview

insert image description here

Time Space Complexity Overview

insert image description here
The following sorting methods are all sorted from small to large.

1.1. Direct insertion sort

algorithm thinking
    1.从位置1的数值n开始,将前面已经遍历过的数值集合看成数组m,则将n往m中插入
    2.n插入到集合m中时从后往前比较,如果比n大则往后移一位,如果比较到比n小,则当前位置就是插入n的位置
    3.通过1、2的操作则可以保证每次插入n后m的集合都是排好的序列
    4.循环1、2、3操作将集合中所有数值均插入一遍即排序完成
Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 直接插入排序:从1开始遍历数组,每个数字都在前面已经遍历的数字中插入
 * 从小到大排序的话碰到比它大的则往后移,直到比它小为止
 */
private void insertSort() {
    
    
    for (int i = 1; i < array.length; i++) {
    
    
        int temp = array[i];
        int j;
        // 在前面已经遍历过的数字中比较若小于则往后移
        for (j = i - 1; j >= 0; j--) {
    
    
            if (temp < array[j]) {
    
    
                array[j + 1] = array[j];
            } else {
    
    
                break;
            }
        }
        array[j + 1] = temp;
    }
}

kotlin language implementation

class Solution {
    fun sortArray(nums: IntArray): IntArray {
        if (null == nums || nums.size == 0) {
            return nums
        }

        for (i in 1 until nums.size) {
            val temp = nums[i]
            for (j: Int in i - 1 downTo 0) {
                if (temp < nums[j]) {
                    nums[j + 1] = nums[j]
                    nums[j] = temp
                } else {

                    break
                }

            }
        }
        return nums
    }
}

1.2. Binary sorting

algorithm thinking

1. The value from position 1 is n, and the value set that has been traversed before is regarded as an array m, and n is inserted into m.
2. When n is inserted into the set m, the dichotomy method is used. First compare the middle value in m. If it is larger than n, continue to compare the middle value of the second half of the set until the left half or right half of the split set is compared. value, the position of the current intermediate value is the position where n is inserted into m.
3. Through the operations of 1 and 2, it can be guaranteed that the set of m after inserting n each time is a sorted sequence.
4. Loop 1, 2, 3 operations to insert all the values ​​in the collection once and the sorting is complete.

Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 二分插入排序:从1开始遍历,已经遍历的数组中头是left,尾是right,遍历到的数字与中间的数字对比
 * 若小于中间的数字则right变更成中间数字前面的一个数字,反之则变更left
 * 直至最后left>right则插入
 */
private void binaryInsertSort() {
    
    
    for (int i = 1; i < array.length; i++) {
    
    
        int temp = array[i];
        int left = 0, right = i - 1;
        int mid;
        while (left <= right) {
    
    
            mid = (left + right) / 2;
            if (temp < array[mid]) {
    
    
                right = mid - 1;
            } else {
    
    
                left = mid + 1;
            }
        }
        // 将遍历到比他大的数字全部往后移一位
        for (int j = i - 1; j >= left; j--) {
    
    
            array[j + 1] = array[j];
        }
        array[left] = temp;
    }
}

2. Hill sort

Quoted into a post: https://www.jianshu.com/p/d730ae586cf3

3. Simple selection sort

algorithm thinking

Sorting from small to large:
1. Find the maximum subscript of all numbers
2. Exchange the position of the subscript of the maximum value with the value at the last position, so that the maximum value found each time is fixed to the end
3. Loop 1, 2 Operate until the traversal finds all

Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 选择排序:找到当前数中最大的数字,找到后与最后一个位置的数字交换位置,直至循环遍历完所有的数为止
 */
private void selectSort() {
    
    

    for (int i = 0; i < array.length; i++) {
    
    

        // 定义最大数字的下标,默认为0
        int max = 0;
        for (int j = 0; j < array.length - i; j++) {
    
    

            // 找到比自己大的数就更新下标
            if (array[max] < array[j]) {
    
    
                max = j;
            }
        }

        // 将找到最大的数与最后一个数字交换位置
        int temp = array[array.length - i - 1];
        array[array.length - i - 1] = array[max];
        array[max] = temp;
    }

}

kotlin language implementation

class Solution {
    fun sortArray(nums: IntArray): IntArray {
        if (null == nums || nums.size == 0) {
            return nums
        }

        var length = nums.size

        while (length > 0) {
            var maxIndex: Int = 0
            for (i: Int in 0 until length) {
                //此处为升序排序
                    //若对数据进行降序排序,改为小于号即可,即 if (nums[i] < nums[maxIndex])
                if (nums[i] > nums[maxIndex]) {
                    maxIndex = i
                }
            }
            var temp = nums[length - 1]
            nums[length - 1] = nums[maxIndex]
            nums[maxIndex] = temp
            length--
        }

        return nums
    }
}

4. Heap sort

Quoted into a post: https://blog.csdn.net/l577217/article/details/80516654

5. Bubble sort

algorithm thinking

1. Two-by-two comparison, if the latter is larger than the former, exchange positions
2. The largest number will come to the end every time you traverse a circle, then determine the maximum value in this round of comparison and put it at the end.
3. Loop 1, 2 until all the

Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 冒泡排序:两两比较,大者交换位置,则每一圈比较最大的数就会冒到最后,循环直至遍历完所有
 */
private void bubbleSort() {
    
    

    for (int i = 0; i < array.length - 1; i++) {
    
    
        for (int j = 0; j < array.length - i - 1; j++) {
    
    
            if (array[j] > array[j + 1]) {
    
    
                int temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    
}

6. Quick Sort

algorithm thinking

1. The idea of ​​quick sorting is mainly to set a reference point m first. Here we assume that the reference point set each time is the first value of each group.
2. Take the reference point m to compare in the set, and find the position where it should be placed.
3. The comparison method is mainly to define the leftmost subscript left in the collection, and the rightmost subscript right, start comparison from the left, if it is smaller than m, then left++, if it finds a larger than m, stop, and assign the value of the left subscript as The value of the right subscript, and then compare right in the same way. If it is larger than m, it will be right–, and if it is found that it is smaller than m, it will be assigned the value of the left subscript. When left==right, the comparison is completed.
4. After the comparison in step 3, you can find the position where the m point is sorted, and then the set is divided into two halves, sorted according to 1, 2, and 3 respectively, and the sorting is completed after recursing to all splits and comparisons.

Step 3 quotes "Aha! Illustration from the book Algorithms. In the figure, the first point 6 is used as the reference point, and the position where 6 should be after sorting is found.
insert image description here
insert image description here
insert image description here
insert image description here

Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 快速排序:找到某个点排序之后它应该所在的位置
 */
private void quickSort() {
    
    
    quickSort(0, array.length - 1);
}

/**
 * 找到开始和结束位置之间以第一个数为基数,这个基数应该所在的位置
 * 找到之后以基数为中心点拆分成前后两段,依次递归进行本操作,直至最后遍历完所有基数为止
 *
 * @param low  开始的点下标
 * @param high 结束的点下标
 */
private void quickSort(int low, int high) {
    
    
    if (low >= high) {
    
    
        return;
    }
    int mid = getMiddle(low, high);
    quickSort(low, mid - 1);
    quickSort(mid + 1, high);
}

/**
 * 通过比较获取最开始基数最后所在的位置
 *
 * @param low  最开始的位置
 * @param high 结束的位置
 * @return 最后基数所在的位置
 */
private int getMiddle(int low, int high) {
    
    
    int temp = array[low];
    while (low < high) {
    
    
        while (low < high && array[high] >= temp) {
    
    
            high--;
        }
        array[low] = array[high];

        while (low < high && array[low] <= temp) {
    
    
            low++;
        }
        array[high] = array[low];
    }
    array[low] = temp;
    return low;
}

7. Merge sort

algorithm thinking

1. Split the data set into two parts.
2. Split the loop until there is only one left in each group.
3. Sort and combine the split arrays.
4. Merge in pairs until they are merged into an array and the sorting is complete.
insert image description here

Code
private int[] array = {
    
    23, 11, 7, 29, 33, 59, 8, 20, 9, 3, 2, 6, 10, 44, 83, 28, 5, 1, 0, 36};

/**
 * 归并排序:将数据集合两分拆开,直至最小之后两两排序合并
 */
private void mergeSort() {
    
    
    int[] temp = new int[array.length];
    mergeSort(temp, 0, array.length - 1);
}


/**
 * 查分数组,如果数组不能拆分了,则直接返回,拆分之后合并
 */
private void mergeSort(int[] temp, int start, int end) {
    
    

    if (start >= end) {
    
    
        return;
    }

    int mid = (start + end) / 2;
    mergeSort(temp, start, mid);
    mergeSort(temp, mid + 1, end);
    mergeArray(temp, start, mid + 1, end);
}


/**
 * 将数组array,以mid为中心,前后两个数组进行合并
 */
private void mergeArray(int[] temp, int start, int mid, int end) {
    
    

    // 定义指针下标,记录前后段是够可以继续移动
    int minA = start, minB = mid;
    for (int i = start; i <= end; i++) {
    
    
        if (minA >= mid || minB > end) {
    
    
            // 如果a或者b用完了,则直接用对方的
            if (minA >= mid) {
    
    
                temp[i] = array[minB];
                minB++;
            } else {
    
    
                temp[i] = array[minA];
                minA++;
            }
        } else {
    
    
            // 都没用完则比较大小
            if (array[minA] < array[minB]) {
    
    
                temp[i] = array[minA];
                minA++;
            } else {
    
    
                temp[i] = array[minB];
                minB++;
            }
        }
    }

    System.arraycopy(temp, start, array, start, end - start + 1);
}

8. Radix sort

Quoted into a post: https://blog.csdn.net/lrxb_123/article/details/115013190

Guess you like

Origin blog.csdn.net/lrxb_123/article/details/114980572