Selection sorting-direct selection and heap sorting

Selection sorting: By selecting the maximum or minimum value in the to-be-sorted sequence each time, and removing it from the queue, it is output to the new sorted sequence. Step by step, until the last element in the sequence to be sorted is selected, the output result is the sorted final result.

Direct selection sort

Direct selection sorting, by traversing the elements in the to-be-sorted sequence each time, selecting the largest or smallest element value, and exchanging it with the element that should be in the position, so the corresponding position of the element is determined. The outer loop starts at a certain end of the sequence, traverses the position to be determined, and executes after nesting

The dynamic demonstration diagram is as follows: the
Direct selection sort
code is implemented as follows:

import java.util.Arrays;

/**
 * @description: select sort method
 * @author: liyaguang
 * @create: 2018-12-03 13:26
 **/
public class SelectSort {
    
    public static void main(String[] args){

        int[] arrOriginal = new int[]{5, 9, 7, 4, 22, 2, 65, 1, 45};
        System.out.println("before select sort, the array is: ");
        System.out.println(Arrays.toString(arrOriginal));

        // 最小元素下标存放临时变量
        int smallestIdx;
        // 每次待确定值的索引位置
        for (int i = 0; i < arrOriginal.length - 1; i++) {
            smallestIdx = i;

            // 遍历待排序序列,选出其中最小元素
            for (int j = i+1; j < arrOriginal.length; j++) {
                if (arrOriginal[j] < arrOriginal[smallestIdx]) {
                    smallestIdx = j;
                }
            }
            
            // 将最小值移动到它对应的索引位置
            Utils.switchVal(arrOriginal, i, smallestIdx);
        }
        System.out.println("\nend select sort, the array is: ");
        System.out.println(Arrays.toString(arrOriginal));
    }
}

The time complexity of direct insertion sorting is O (n 2 ).

Heap sort

Heap sorting: In the idea of ​​direct selection sorting, using the characteristics of the heap data structure, you can directly select the largest or smallest element. The heap is a special kind of complete binary tree, divided into the largest heap or the smallest heap, the parent node value of the largest heap> = two child node values, the parent node value of the smallest heap <= two child node values. Later the meaning of heap was extended to the garbage collection area in programming languages.

The main key of the algorithm is to construct a data structure such as a heap. The following demonstrates the code for heap sorting by using the largest heap. The maximum heap data structure is implemented by an array, and the number of elements in the maximum heap should be less than or equal to the number of array elements, which is expressed by the heapSize property in the Heap class object

The dynamic demonstration diagram is as follows: the
Heap sort
code is implemented as follows:

  1. Implementation of maximum heap data structure
/**
 * max heap data structure
 *
 * @author liyaguang
 */
public class Heap {
    private int heapSize;

    public int getHeapSize() {
        return heapSize;
    }

    public void setHeapSize(int size) {
        this.heapSize = size;
    }

    public int getParentIdx(int i) {
        return i / 2;
    }

    public int getLeftIdx(int i) {
        return 2 * i;
    }

    public int getRightIdx(int i) {
        return 2 * i + 1;
    }

    /**
     * 调整最大堆,使其符合数据结构要求
     *
     * @param arr 源数组
     * @param i   待调整元素在数组中的元素下标
     */
    public void maxHeapify(int[] arr, int i) {
        int left = getLeftIdx(i);
        int right = getRightIdx(i);
        int largest = i;
        if (left < heapSize && arr[left] > arr[largest]) {
            largest = left;
        }
        if (right < heapSize && arr[right] > arr[largest]) {
            largest = right;
        }
        if (largest != i) {
            Utils.switchVal(arr, i, largest);
            maxHeapify(arr, largest);
        }
    }

    /**
     * 构建最大堆
     *
     * @param arr 源数组
     */
    public void buildMaxHeap(int[] arr) {
        this.setHeapSize(arr.length);
        for (int i = (arr.length / 2); i >= 0; i--) {
            maxHeapify(arr, i);
        }
    }
}
  1. The main algorithm of heap sorting based on the maximum heap data structure
import java.util.Arrays;

/**
 * heap sort algorithm
 *
 * @author liyaguang
 */
public class HeapSort {

    public static void main(String[] args) {

        int[] arr = new int[]{5, 9, 7, 4, 22, 2, 65, 1, 45};
        System.out.println("before select sort, the array is: ");
        System.out.println(Arrays.toString(arr));

        // 建最大堆
        Heap heap = new Heap();
        heap.buildMaxHeap(arr);

        // 选取堆顶最大元素,放置到数组对应位置后,调整最大堆
        for (int i = arr.length - 1; i > 0; i--) {
            Utils.switchVal(arr, i, 0);
            heap.setHeapSize(heap.getHeapSize() - 1);
            heap.maxHeapify(arr, 0);
        }

        System.out.println("\nend heap sort, the array is: ");
        System.out.println(Arrays.toString(arr));
    }

}

The heap sorting time complexity is: O (nlogn)

summary

By selecting the best value each time, directly select the method used for sorting-traversal, and heap sorting is based on an already ordered data structure, and after selecting the best value each time, adjusting the heap structure is Based on the already partly orderly basis, a lot of comparisons are made less, which improves the operating efficiency.

Reference:
"Introduction to Algorithms"
Selection sort-wikiwand
Heapsort-wikiwand

Sample code download for this series: welcome to follow my github

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

Guess you like

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