[Sorting algorithm 1] Three classic sorting algorithms: bubble sorting, selection sorting, insertion sorting

Preface: Bubble sorting, selection sorting, and insertion sorting are the three most basic sorting algorithms. In fact, as long as the algorithm has a clear idea, the code implementation of the algorithm will be very simple and logical. Below, the editor will lead you to analyze how to understand the ideas of these three sorting algorithms so that you can grasp them more deeply. In addition, readers are very welcome to criticize and correct the content of the article, thank you!

Table of contents

1. Bubble sort

1.1 Algorithm ideas

1.2 Code implementation

2. Selection sort

2.1 Algorithm ideas

2.2 Code implementation

3. Insertion sort

3.1 Algorithm ideas

3.2 Code implementation


1. Bubble sort

        Bubble sorting is a sorting algorithm with a time complexity of O(N*2) and a space complexity of O(1), and it is stable. With the rapid development of hardware memory technology, our choice of algorithm is more focused on choosing an algorithm with low time complexity, that is, the code runs fast. Obviously, bubble sorting is not a good choice. Of course, this must fully consider the project. Actual demand.

1.1 Algorithm ideas

        Assuming that an array of length N is sorted, the process of implementing the bubble sort algorithm is:

①Traversing in the range of array index 0-N-1, each element in the array is compared with the next element, if the current element is greater than the value of the next element, the positions of the two are exchanged, and vice versa. After the traversal, the last element must be the largest number, thus determining the position of the largest number in 0-N-1, at the end of the array;

②Traversing in the range of array index 0-N-2, the judgment method is the same as in ①

……

③Traversing in the range of array index 0-1, the judgment method is the same as in ①

The new array finally obtained is a sorted array. This sorting algorithm is called bubble sorting. Each traversal can only determine the position of the largest number within the traversal range.

1.2 Code implementation

//冒泡算法
public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        if (arr == null || n < 2) {
            System.out.println("数组太小,不能排序");
            return;
        }
        for (int i = n - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    //交换两个数
    public static void swap(int[] arr, int i, int j) {
        //这里用到的是异或^的性质,①0^a=a;②a^a=0;③交换律:(a^b)^c=(a^c)^b
        //注意:在数组中能用^交换两个数的位置前提是索引i!=j
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }

    //代码测试
    public static void main(String[] args) {
        int[] arr = {2, 15, 4, 7, 36, 1, 64, 42};
        bubbleSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
}

operation result:

2. Selection sort

           Selection sorting is also a sorting algorithm with a time complexity of O(N*2) and a space complexity of O(1), but it is not stable.

2.1 Algorithm ideas

        Assuming that an array of length N is sorted, the process of selection sorting algorithm is to select the smallest number among iN-1 numbers and put it on arr[i], where i∈[0, N-1], that is:

①Traversing from 0 to N-1, select the smallest number and put it on arr[0];

②Traversing from 1 to N-1, select the smallest number and place it on arr[1];

……

③Traverse through N-2~N-1, select the smallest number and put it on arr[N-2]

The final new array obtained is a sorted array. This sorting algorithm is called selection sorting. Each traversal can only determine the position of the smallest number within the traversal range.

2.2 Code implementation

//选择排序
public class SelectSort {
    public static void selectSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            swap(arr, i, minIndex);
        }
    }

    //交换两个数的位置
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    //代码测试
    public static void main(String[] args) {
        int[] arr = {2, 15, 4, 7, 36, 1, 64, 42};
        selectSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
    }
}

operation result:

3. Insertion sort

        Insertion sorting is also a sorting algorithm with a time complexity of O(N*2) and a space complexity of O(1), and it is stable.

3.1 Algorithm ideas

        Assuming that an array of length N is sorted, the implementation process of the insertion sort algorithm is:

① First ensure that the array is ordered in the 0-1 position;

②Ensure that the array is ordered in the 0-2 position;

……

③Ensure that the array is ordered in the 0-N-1 position

The final new array is the sorted array, this sorting algorithm is called insertion sort

3.2 Code implementation

//插入排序
public class InsertSort {
    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                } else {
                    break;
                }
                //else后面部分的语句其实有没有不影响排序,但是当数组很大时可以明显加快运行速度,
                // 因为i前面的数(不包括i)已经做到有序了,如果可以保证i(这里等同于j+1)上的数比i-1(这里等同于j)上的数大,
                //那么0-i上的数就都有序了,没必要再继续遍历比较下去,此处的break跳出第二个循环进入第一个循环中。
            }
        }
    }

    //交换两个数的位置
    public static void swap(int[] arr, int i, int j) {
        int temp;
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    //代码测试
    public static void main(String[] args) {
        int[] arr = {7, 2, 8, 12, 6, 9, 4, 2, 6, 15, 3, 27};
        insertSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

operation result:

Guess you like

Origin blog.csdn.net/Mike_honor/article/details/125756472