Java implements commonly used sorting algorithms (bubble sort, selection sort, insertion sort, Hill sort)

Common Sorting Algorithms

insert image description here

Time Complexity of Sorting Algorithm

Sorting Algorithm Average time worst time stability space complexity Remark
Bubble Sort O(n2) O(n2) Stablize O(1) better when n is small
swap sort O(n2) O(n2) unstable O(1) n good when small
selection sort O(n2) O(n2) unstable O(1) n good when small
insertion sort O(n2) O(n2) Stablize O(1) mostly in order
radix sort O(n*k) O(n*k) Stablize O(n) Two-dimensional array (bucket), one-dimensional array (position of the first element in the bucket)
Hill sort O(nlogn) O(ns)(1<s<2) unstable O(1) s is the selected group
quick sort O(nlogn) O(n2) unstable O(logn) better when n is bigger
merge sort O(nlogn) O(nlogn) Stablize O(1) better when n is bigger
heap sort O(nlogn) O(nlogn) unstable O(1) better when n is bigger

Bubble Sort

1 Introduction

Bubble Sort is a relatively simple sorting algorithm in the field of computer science.
It repeatedly visits the column of elements to be sorted, compares two adjacent elements in turn, and exchanges them if the order (such as from large to small, initial letter from Z to A) is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged, that is to say, the element column has been sorted.
The name of this algorithm comes from the fact that the smaller elements will slowly "float" to the top of the sequence (in ascending or descending order) through exchange, just like the bubbles of carbon dioxide in carbonated drinks will eventually float to the top, hence the name "bubbling". Sort".

2. Thinking analysis

  • Compare two adjacent elements, if the first is greater than the second then swap the positions
  • Perform this operation on each subsequent element until the last one ends the first cycle, so that the last element must belargest element, so it is not necessary to compare the last element in subsequent loop comparisons
  • Repeat the above steps to excludethe last element of the previous loop,soinner loopwill be less and less
  • until there are no pairs of numbers to compare
  • outer loopThe number of times is the number of array elements - 1 , and == the number of inner loop comparisons is getting smaller and smaller each time –
  • Optimization: if in a certainElements are not swapped in the outer loop, proves that it is already an ordered array, then the loop can be ended

3. Diagram

1. The first cycle (yellow represents the exchange position, red represents the final position)

insert image description here

2. The second cycle

insert image description here

3. The third cycle

insert image description here

4. The fourth cycle

insert image description here
end loop

4. Code implementation

/**
 * 冒泡排序
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/7
 */
public class Bubbling {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,9,-1,7,21};
        // 外层循环次数为数组的长度-1
        for (int i = 0; i < arr.length - 1; i++) {
    
    
            // 内层循环次数,每次都会减少
            for (int j = 0; j < arr.length - 1 - i; j++) {
    
    
                // 交换位置
                if (arr[j] > arr[j+1]){
    
    
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }

        // 打印
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+" ");
        }
    }

}

Optimization: If it is found that the position of the array elements has not changed after the end of a certain outer loop, then the loop ends and it is already an ordered array

code:

/**
 * 冒泡排序
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/7
 */
public class Bubbling {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,9,-1,7,21};
        // 外层循环次数为数组的长度-1
        for (int i = 0; i < arr.length - 1; i++) {
    
    
            // 如果内层循环没有交换位置,那么已经是有序数组,结束循环
            boolean flag = true;
            // 内层循环次数,每次都会减少
            for (int j = 0; j < arr.length - 1 - i; j++) {
    
    
                // 交换位置
                if (arr[j] > arr[j+1]){
    
    
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    flag = false;
                }
            }
            if (flag){
    
    
                break;
            }
        }

        // 打印
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+" ");
        }
    }

}

selection sort

1 Introduction

Selection sort is a simple and intuitive sorting algorithm. Its working principle is: select the smallest (or largest) element from the data elements to be sorted for the first time, store it in the starting position of the sequence, and then find the smallest (largest) element from the remaining unsorted elements element and put it at the end of the sorted sequence. And so on, until the number of all data elements to be sorted is zero. Selection sort is an unstable sorting method.

2. Thinking analysis

2.1 Exchange data for the first time

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/7
 */
public class Deduction {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    8,3,2,1,7,4,6,5};
        // 记录最小数的下标
        int min;
        // 假设min=0开始
        min = 0;
        // 既然我们都假设下标为0的是最小,那么就从他后面开始比较
        for (int i = 1; i < arr.length; i++) {
    
    
            // 如果后面的元素中有小于的元素,记住的他下标
            if (arr[min] > arr[i]){
    
    
                min = i;
            }
        }
        // 交换
        int temp = arr[0];
        arr[0] = arr[min];
        arr[min] = temp;

        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i] + " ");
        }

        // 打印获取到 1 3 2 8 7 4 6 5 

    }
}

2.2 The second time starts from i+1

/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/7
 */
public class Deduction {
    
    
    public static void main(String[] args) {
    
    
//        int[] arr = {8,3,2,1,7,4,6,5};
        int[] arr = {
    
    1,3,2,8,7,4,6,5};
        // 记录最小数的下标
        int min;
        // 假设min=1开始
        min = 1;
        // 既然我们都假设下标为1的是最小,那么就从他后面开始比较
        for (int i = 2; i < arr.length; i++) {
    
    
            // 如果后面的元素中有小于的元素,记住的他下标
            if (arr[min] > arr[i]){
    
    
                min = i;
            }
        }
        // 交换
        int temp = arr[1];
        arr[1] = arr[min];
        arr[min] = temp;

        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i] + " ");
        }

        // 打印获取到 1 2 3 8 7 4 6 5 

    }
}

and so on

2.3 Summary

  • i starts from 0, assumingmin represents the index of the minimum value, initially assumingmin = i, ThenFind the subscript of the smallest element in the following array, let min = minIndex, exchange positions,Note that when looking for the minimum index subscript, the positions of other elements cannot be moved
  • Then the array moves backwards, because the first number is already the smallest number, there is no need to compare it, starting from i+1
  • Repeat the above steps until the sorting ends
  • A total of traversal of the length of the array is required - 1 time.

3. Diagram

insert image description here

4. Code implementation


/**
 * 选择排序
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/7
 */
public class Choice {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    8,3,2,1,7,4,6,5};
        // 记录最小数的下标
        int min;
        // 外层循环次数为数组长度 - 1
        for (int i = 0; i < arr.length - 1; i++) {
    
    
            min = i;
            // 内层循环每次都是从i+1开始
            for (int j = i+1; j < arr.length; j++) {
    
    
                // 找出最小数的下标
                if (arr[min] > arr[j]){
    
    
                    min = j;
                }
            }
            // 如果不是同一个数,那么就交换位置
            if (min != i){
    
    
                int temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
            }
        }
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+" ");
        }
    }
}

insertion sort

1 Introduction

Insertion sorting is also generally called direct insertion sorting. It is an efficient algorithm for sorting a small number of elements. Insertion sorting is the simplest sorting method, its basic idea is to insert a record intoin sorted ordered list, so as to create a new ordered list with the number of records incremented by 1. In the implementation process, a double-layer loop is used. The outer loop searches for all elements except the first element, and the inner loop searches for the position to be inserted in the ordered list in front of the current element and moves it.

2. Thinking analysis

  • because the original arrayfirst elementasthe first element of an ordered list, so start directly from the element with index 1, when 1 is inserted as an element to compare with the last element in the ordered list
  • ifinsert element less than, then in the ordered listThe last element will be shifted one bit backward, until a position in the ordered list is found where the element is no greater than the inserted element, orindex less than 0, end the comparison
  • Then assign the inserted element

3. Diagram

Note that the red array here represents already an ordered list element

3.1 First round

insert image description here

3.2 Second round

insert image description here

3.3 The third round

insert image description here

3.4 Fourth round

insert image description here

4. Code implementation

/**
 * 插入排序
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/9
 */
public class InsertSorted {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3, 1, 6, 10, 2};

        for (int i = 1; i < arr.length; i++) {
    
    
            // 保留即将插入元素的值
            int insertValue = arr[i];
            // 当前索引
            int index = i;
            // 1.如果索引大于0,说明还没遍历完
            // 2.如果插入的值小于有序列表中的值,那么久有序列表中大于插入元素的元素,就要后移
            while (index > 0 && insertValue < arr[index-1]){
    
    
                arr[index] = arr[index-1];
                index --;
            }
            // 直到找到插入元素不大于有序列表中元素的位置
            arr[index] = insertValue;

        }
		// 打印
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i] + " ");
        }

    }
}


Hill sort

1 Introduction

Shell's Sort is a kind of insertion sort, also known as "Diminishing Increment Sort", which is a more efficient and improved version of the direct insertion sort algorithm. Hill sort is an unstable sorting algorithm.
Hill sorting is to group the records by a certain increment of the subscript, and use the direct insertion sorting algorithm to sort each group; as the increment gradually decreases, each group contains more and more keywords. When the increment is reduced to 1, The algorithm terminates when the entire data has just been divided into one group.

2. Thinking analysis

  • Select an incremental sequence t1 (generally array length/2), t2 (generally a group length/2), ..., tk, where ti > tj, tk = 1;
  • According to the incremental sequence number k, sort the sequence k times;
  • For each sorting, according to the corresponding increment ti, the column to be sorted is divided into several subsequences of length m, and direct insertion sorting is performed on each sublist respectively. Only when the increment factor is 1, the entire sequence is treated as a table, and the length of the table is the length of the entire sequence.

3. Diagram

3.1 First round

The increment is 3, and the comparison starts directly from arr[3], and it is found that arr[3] > arr[0], there is no need to change the position, and arr[4] < arr[1] needs to be changed after the position is changed,
insert image description here
continue Compare

insert image description here

Until arr[6]<arr[3], exchange positions
insert image description here
and then we find that arr[3] can be compared with arr[0] because index-gap >= 0 can continue to compare

insert image description here

3.2 Second round

Start comparing from arr[1], and compare backwards one by one until arr[6] < arr[5]

insert image description here

After exchanging positions, compare arr[5] with arr[4] and exchange positions
insert image description here

Finish
insert image description here

4. Code implementation

/**
 * 希尔排序
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/9/9
 */
public class ShellInsert {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    23,34,21,31,18,98,10};
        // 增量
        int gap = arr.length/2;
        // 只要增量大于等于1就继续分组
        while (gap >= 1){
    
    

            // 从索引=增量开始,依次往后
            for (int i = gap; i < arr.length; i++) {
    
    
                // 定义一个变量,防止下面代码影响原 i 的值
                int j = i;
                // 只有 arr[j] < arr[j-gap] 交换位置 ,而且可能一次不一定能比较完,需要多次比较 j-gap >= 0
                while (j-gap >= 0 && arr[j] < arr[j-gap]){
    
    
                    // 交换
                    int temp = arr[j];
                    arr[j] = arr[j-gap];
                    arr[j-gap] = temp;
                    // 假设 j = 6 时,可以多次执行
                    j -= gap;
                }
            }

            // 控制增量
            gap /= 2;

        }

        // 打印
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+" ");
        }

    }
}

Guess you like

Origin blog.csdn.net/weixin_46073538/article/details/126740493