Sorting algorithm (1)-bubbling, insertion, selection

Insert picture description here

For the sake of simplicity, all examples are in positive order by default, and the problem of positive order and reverse order is not considered here! !

ready

Before starting, I made the following preparations here:

  • A powered computer
  • JDK8 OR JDK11
  • JUnit5
  • Idea
  • lombok (not required, I am used to using this to print logs)

An abstract interface:

public interface Sort<E> {
    
    
    E[] sort();
}

A test case:

@Slf4j
class SortTest {
    
    
    Integer[] integers;

    Sort<Integer> sort;

    @BeforeEach
    void setUp() {
    
    
        integers = new Integer[]{
    
    3, 7, 2, 1, 4, 8, 9, 8, 5, 6, 0};
        log.info("排序前: {}", Arrays.toString(integers));
    }

    @AfterEach
    void tearDown() {
    
    
        assertSort(sort.sort());
    }

    @Test
    void bubbleSortTest() {
    
    
        sort = new BubbleSort(integers);
    }

    @Test
    void insertSortTest() {
    
    
        sort = new InsertSort(integers);
    }

    @Test
    void selectSortTest() {
    
    
        sort = new SelectSort(integers);
    }

    private void assertSort(Integer[] sort) {
    
    
        log.info("排序后: {}", Arrays.toString(sort));
        assertAll(
                () -> assertEquals(integers.length, sort.length),
                () -> assertEquals(0, sort[0]),
                () -> assertEquals(9, sort[sort.length - 1]),
                () -> assertEquals(1, sort[1]),
                () -> assertEquals(2, sort[2]),
                () -> assertEquals(3, sort[3]),
                () -> assertEquals(4, sort[4]),
                () -> assertEquals(5, sort[5]),
                () -> assertEquals(6, sort[6]),
                () -> assertEquals(7, sort[7]),
                () -> assertEquals(8, sort[8]),
                () -> assertEquals(8, sort[9])
        );
    }
}

Bubble Sort

For bubble sorting, all descriptions are pale, watch this magical video, you will fully understand

https://www.bilibili.com/video/BV1xW411Y7VL

public class BubbleSort implements Sort<Integer> {
    
    

    private final Integer[] elements;

    public BubbleSort(Integer[] elements) {
    
    
        this.elements = elements;
    }

    @Override
    public Integer[] sort() {
    
    
        int length = elements.length;
        for (int i = 0; i < length - 1; i++) {
    
    
            for (int j = 0; j < length - i - 1; j++) {
    
    
                // 当前大于下一位,则互换位置,继续向后比较
                if (elements[j] > elements[j + 1]) {
    
    
                    Integer temp = elements[j];
                    elements[j] = elements[j + 1];
                    elements[j + 1] = temp;
                }
                // 当前小于或等于下一位,从下一位开始往后比较
            }
        }
        return elements;
    }
}

Insertion sort

  1. Insertion sort divides the array into two areas, the sorted area, and the unsorted area
  2. When sorting starts, the first element of the array is in the sorted area by default
  3. In each round of sorting, the first element in the unsorted area is compared with the elements in the sorted area in turn. If the unsorted element is smaller than the currently sorted element, this is the insertion point
    • The element after the insertion point is shifted backward
    • Insert unsorted elements here
  4. Otherwise, this unsorted element is inserted at the end of the sorted area, that is, the array is not moved, and a new round of comparison is performed on the next bit of the unsorted area
public class InsertSort implements Sort<Integer> {
    
    

    private Integer[] elements;

    public InsertSort(Integer[] elements) {
    
    
        this.elements = elements;
    }

    @Override
    public Integer[] sort() {
    
    
        int sortedLength = 1;
        int unSortedLength = elements.length - 1;

        for (int i = 0; i < unSortedLength; i++) {
    
    
            // 未排序区的第一个元素
            Integer unSort = elements[sortedLength];
            // 与已排序元素比较
            for (int j = 0; j < sortedLength; j++) {
    
    
                // 1. 已排序区:如果unSort比所有的都大,则排在最后一位,直接完成本轮比对即可
                // 2. 已排序区:unSort小于此位数,则排在此位前
                if (unSort < elements[j]) {
    
    
                    rightMoveOnePlace(sortedLength, j, elements);
                    elements[j] = unSort;
                    break;
                }
                // 3. 已排序区:unSort大于此位数,则进行下一位数对比
            }
            sortedLength++;
        }

        return elements;
    }

    /**
     * 将数组从指定位置开始,向右移动1位
     *
     * @param endMoveElementIndex   结束移动的元素数量
     * @param startMoveElementIndex 开始移动的元素位置
     * @param elements                  待操作的数组
     */
    private void rightMoveOnePlace(int endMoveElementIndex, int startMoveElementIndex, Integer[] elements) {
    
    
        for (int k = 0; k < endMoveElementIndex - startMoveElementIndex; k++) {
    
    
            elements[endMoveElementIndex - k] = elements[endMoveElementIndex - k - 1];
        }
    }
}

Select sort

  1. Selection sort is also divided into sorted area and unsorted area
  2. When sorting starts, there are no elements in the unsorted area
  3. Starting from the first element in the unsorted area, compare with all subsequent elements in turn, and put the smallest element at the end of the sorted area
public class SelectSort implements Sort<Integer> {
    
    

    private Integer[] elements;

    public SelectSort(Integer[] elements) {
    
    
        this.elements = elements;
    }

    @Override
    public Integer[] sort() {
    
    
        for (int unSortIndex = 0; unSortIndex < elements.length - 1; unSortIndex++) {
    
    
            int min = elements[unSortIndex];
            int minIndex = unSortIndex;
            for (int j = unSortIndex + 1; j < elements.length; j++) {
    
    
                if (elements[j] < min) {
    
    
                    min = elements[j];
                    minIndex = j;
                }
            }
            // 如果相等,则说明未排序区首位元素已经是最小值,不需要交换位置
            if (minIndex != unSortIndex) {
    
    
                elements[minIndex] = elements[unSortIndex];
                elements[unSortIndex] = min;
            }
        }
        return elements;
    }
}

At last

The time complexity of these sorting algorithms is O (n 2) O(n^2)O ( n2)

No new array space is applied for in the sorting process. They are all sorted on the basis of the original array, so these are all in-situ sorting algorithms, and their space complexity is O (n) O(n)O ( n )

Next, let’s take a look at merging and fast sorting

If you feel helpful to yourself, please give a like, this will be my biggest encouragement~~~

Guess you like

Origin blog.csdn.net/weixin_38403680/article/details/113998077