Exchange sorting-bubble sorting and quick sorting

Exchange order

The basic idea of ​​exchange sorting is to compare the key codes of the sequence records to be sorted pair by pair. If the records are reversed, they are exchanged until there is no reverse pair. Bubble sort and quick sort are typical exchange sort algorithms.

Bubble Sort

Bubble sorting and direct insertion sorting are perhaps the most commonly used sorting methods in our lives. Bubble sorting consists of two layers of nested loops: the outer loop determines a position at a time, and the inner loop is relative to the outer layer, from the opposite direction. The adjacent elements are compared one by one until the current position of the outer layer, and then the corresponding value is obtained.

The dynamic presentation diagram is as follows: the
Bubble Sort
code is implemented as follows (in the opposite direction of the dynamic presentation diagram sorting):

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args){
		// 待排序列
        int[] arrOriginal = new int[]{5, 9, 7, 4, 22, 2, 65, 1, 45};
        System.out.println("before sort, the array is: ");
        System.out.println(Arrays.toString(arrOriginal));

		// 临时变量,内层循环中交换元素时应用
        int temp = 0;
        boolean noSwap;
        // 外层:从某一端开始,确定要排序的某个位置
        for (int i = 0; i < arrOriginal.length; i++) {
        	noSwap = true;
        	// 内层:从另一端开始,确定外层位置对应的值
            for (int j = arrOriginal.length - 1 ; j > i; j--) {
                if(arrOriginal[j] < arrOriginal[j-1]){
                    temp = arrOriginal[j];
                    arrOriginal[j] = arrOriginal[j-1];
                    arrOriginal[j-1] = temp;
                    noSwap = false;
                }
            }
            if(noSwap) {
                break;
            }
        }
        System.out.println("\nend sort, the array is: ");
        System.out.println(Arrays.toString(arrOriginal));
    }
}

As with direct insertion sorting, the optimal time complexity is O (n) and the average and worst case are O (n 2 ).

Quick sort

Quick sorting, invented in 1962, embodies the idea of ​​divide and conquer: first, select the axis value; then, compare the sequence elements to be sorted with the axis value respectively, divide it into both sides of the axis value, and fix the position of the axis value element; finally, aim at The left and right sides recursively call the quick sort algorithm until the number of sequence elements to be sorted is less than 2.

The dynamic demonstration diagram is as follows: the
Quick Sort Algorithm
code is implemented as follows:

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args){
        int[] arrOriginal = new int[]{5, 9, 7, 4, 22, 2, 65, 1, 45};
        System.out.println("before sort, the arr is: ");
        System.out.println(Arrays.toString(arrOriginal));

        quickSortProcess(arrOriginal, 0, arrOriginal.length-1);

        System.out.println("end sort, the arr is: ");
        System.out.println(Arrays.toString(arrOriginal));
    }

    public static void quickSortProcess(int[] arr, int startIdx, int endIdx) {
        if (startIdx >= endIdx){
            return;
        }
        // 1. 选择轴值
        int flagIndex = (startIdx + endIdx) / 2;
        int flagValue = arr[flagIndex];

        
        // 2. 将轴值与末尾元素交换,确定一个可交换的元素
        switchVal(arr, flagIndex, endIdx);
        // 设定正向与反向游标指针
        int forwardIdx = startIdx;
        int reverseIdx = endIdx;
        // while 正idx < 反idx
        while(forwardIdx < reverseIdx) {
            // 正向从起始元素开始,遇到比轴值大的元素时,与反向指针元素交换位置,正向指针暂停,break;否则正向+1
            while(forwardIdx < reverseIdx && arr[forwardIdx] < flagValue){
                forwardIdx++;
            }
            switchVal(arr, forwardIdx, reverseIdx);

            // 反向从结束元素开始,遇。。。。小。。。。,。正。。。。。。。。。,反向指针暂停,break;。。反向-1
            while(forwardIdx < reverseIdx && arr[reverseIdx] > flagValue){
                reverseIdx--;
            }
            switchVal(arr, forwardIdx, reverseIdx);
        }

        // 3. 二分,递归调用(注释代码为错误示范,出现堆栈溢出的异常)
        // quickSortProcess(arr, startIdx, endIdx/2);
        // quickSortProcess(arr, (endIdx/2 + 1), endIdx);
        quickSortProcess(arr, startIdx, forwardIdx);
        quickSortProcess(arr, forwardIdx+1, endIdx);
    }

    public static void switchVal(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}

The quick sort time complexity is: the worst case is O (n 2 ), and the best and average case is O (nlogn)

summary

Both bubbling and quick sorting are based on the idea of ​​exchange sorting, and provide different implementations. Among them, bubbling is based on the sorting idea in our decimal world, picking the largest or smallest each time, and then looking for the next largest or the largest from the remaining data items. It is the second smallest, so it is a stable sort, but this intuitive idea has a time complexity of the square level and is not suitable for large data volumes.
Quick sorting uses the idea of ​​divide and conquer. Through top-down splitting, the sorting problem is reduced in size. While completing small-scale sorting, the overall sorting effect is finally achieved and the execution is more efficient.

Reference:
"Data Structure and Algorithm"
Bubble sort-wikiwand
Quicksort-wikiwand

Series sample code download: welcome to follow my github

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/86619723