Simple algorithms - direct insertion, bubbling, direct selection

There are many sorting algorithms.
write picture description here
Among them , direct insertion sorting, direct selection sorting, and bubble sorting are simple sorting. They do not require high space, but their time efficiency is unstable.
This article will introduce three simple sorting, and the next one will introduce three. The advanced sorting quicksort, hill sort, heap sort
corresponding to simple sorting First make a common element exchange implementation function, the following swap calls are all this

 /**
     * 交换数组元素
     * 交换思想很简单 数字x y  =>  x=x+y;y=x-y;x=x-y;
     * 这种方法不使用临时变量,能有效降低算法空间复杂度,但也有缺点,比如可能存在越界风险
     * @param arr
     * @param a
     * @param b
     */
    public void swap(int []arr,int a,int b){
        arr[a] = arr[a]+arr[b];
        arr[b] = arr[a]-arr[b];
        arr[a] = arr[a]-arr[b];
    }

Bubble Sort

The name of this algorithm comes from the fact that larger elements will slowly "float" to the top of the sequence by swapping, hence the name "bubble sort".
Basic operations:
1. Compare adjacent elements. If the first is bigger than the second, swap the two of them.
2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time, until there is no pair of numbers to compare.
For example :
the original array: 5 3 6 4 The
first step: 3 5 4 6 The
second step: 3 4 5 6 (Actually the sorting has ended here, but the original bubble sort will go through all the loops)
Step 3: 3 4 5 6
Step 4: 3 4 5 6

Program implementation

    int arr[] = {5,3,6,4};
    public void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            //每次将最大的数字移到最后,下次循环长度-1,再将剩余数组中最大的数字移到剩余数组长度的后面
            for (int j = 0; j < arr.length - i -1; j++) {
                if(arr[j] > arr[j + 1]) {
                    swap(arr, j, j+1);
                }
            }
        }
       // printArr(arr);
    }

It can also be optimized to stop the loop if the sorting is done:

    public void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = true;//设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已然完成。
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr,j,j+1);
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
    }

direct insertion sort

The basic operation is to insert a record into the sorted sorted table to get a new sorted list with the number of records increased by 1. Such as:

Original array: 5 3 6 4
First step: 5 - - - 3 6 4
Second step: 3 5 - - - 6 4 (3 and 5 are compared once)
Third step: 3 5 6 - - - 4 (6 and 5 compare once)
Step 4: 3 4 5 6 (4 and 3 5 6 are compared once each)

Program implementation

    int arr[] = {5,3,6,4};
    /**
     * 采用直接插入排序 将数组按升序排列
     * @param arr
     */
    private void directInSert(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int j = i;
            while (j > 0 && arr[j] < arr[j - 1]){//两层意思:1、如果是第一个元素就放着 不比较也不交换 2、如果后面一个数字小于前面那个 就进行交换
                swap(arr, j, j-1);
                j--;
            }
        }
    }

It can also be done like this:

    int arr[] = {5,3,6,4};
    public void insertSort(int[] arr) {
        int j;
        for (int i = 0; i < arr.length; i++) {
            int tem = arr[i];
            for (j = i; j > 0 && tem < arr[j - 1]; j--) {
                arr[j] = arr[j - 1];
            }
            arr[j] = tem;
        }
        //printArr(arr);
    }

direct selection sort

The basic idea is: select the minimum value from R[0]~R[n-1] for the first time, exchange it with R[0], and select the minimum value from R[1]~R[n-1] for the second time , exchange with R[1], …., select the minimum value from R[i-1]~R[n-1] for the i-th time, exchange with R[i-1], ….., n-1th Select the minimum value from R[n-2]~R[n-1], exchange it with R[n-2], and pass through n-1 times in total to obtain an ordered sequence arranged according to the sorting code from small to large. For example:
original array: 5 3 6 4
Step 1: [ 3 ] 5 6 4 (select the minimum value 3 and swap the first number 5)
Step 2: [ 3 4 ] 6 5 (select the minimum value 4 and The second number 5 is exchanged)
The third step: [ 3 4 5 ] 6 (choose the minimum value of 5 and the third number 6 is exchanged)
The fourth step: [ 3 4 5 6 ]

Program implementation

    public void straightSelection(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int tem = i;//存放较小元素下标
            for (int j = i + 1; j < arr.length; j++){
                if (arr[j] < arr[tem]) {
                    tem = j;
                }
            }
            if (tem != i) {
                swap(arr, i, tem);
            }
        }
        printArr(arr);
    }

The above three sorting are simple sorting, all of which are stable, and the time complexity is O(n^2). The average space complexity is O(1).

Reference: Graphical sorting series of
Baidu Encyclopedia
dreamcatcher-cx

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325655550&siteId=291194637