8. Sort - heap row

heap sort

  Heap sort is a sorting algorithm designed by using the data structure of heap . Heap sort is a selection sort. Its worst and best, the average time complexity is O(nlogn) , and it is also unstable sorting. First, a brief understanding of the heap structure.

heap

  A heap is a complete binary tree with the following properties: the value of each node is greater than or equal to the value of its left and right child nodes, which is called a big top heap; or the value of each node is less than or equal to the value of its left and right child nodes value, called the small top heap. As shown below:

At the same time, we number the nodes in the heap by layer, and map this logical structure to the array as follows

The array is logically a heap structure. We use a simple formula to describe the definition of the heap:

大顶堆:arr[i] >= arr[2i+1] && arr[i] >=arr[2i+2]  

小顶堆:arr[i] <= arr[2i+1] && arr[i] <=arr[2i+2]  

ok , got the definitions. Next, let's take a look at the basic idea and basic steps of heap sorting:

The basic idea and steps of heap sorting

  The basic idea of ​​heap sorting is to construct the sequence to be sorted into a large top heap. At this time, the maximum value of the entire sequence is the root node of the top of the heap. Swap it with the element at the end, where the end is the maximum value. The remaining n-1 elements are then reconstructed into a heap, which results in the next smallest value of n elements. This repeated execution, you can get an ordered sequence

Step 1 Construct the initial heap. Constructs a given unordered sequence into a large top heap (generally a large top heap is used for ascending order, and a small top heap is used for descending order) .

  a. Suppose the given unordered sequence structure is as follows

2. At this point, we start from the last non-leaf node (the leaf node naturally does not need to be adjusted, the first non-leaf node arr.length/2-1=5/2-1=1 , which is the following 6 nodes point), adjust from left to right, bottom to top.

3. Find the second non-leaf node 4 , since 9 elements in [4, 9, 8] are the largest, 4 and 9 are swapped.

At this time, the exchange caused the structure of the sub-root [4, 5, 6] to be chaotic, and continued to adjust. In [4, 5, 6], 6 was the largest, and 4 and 6 were exchanged.

At this point, we have constructed an unnecessary sequence into a large top heap.

Step 2: Swap the top element of the heap with the last element to make the last element the largest. Then continue to adjust the heap, and then swap the top element of the heap with the last element to get the second largest element. Swap, rebuild, swap over and over again.

a. Swap the top element 9 and the end element 4 of the heap

b. Readjust the structure so that it continues to satisfy the heap definition

c. Swap the top element 8 with the last element 5 to get the second largest element 8.

The subsequent process, continue to adjust, exchange, and so on, and finally make the entire sequence orderly

Then briefly summarize the basic idea of ​​heap sort:

  a. Build the unneeded sequence into a heap, and select a large top heap or a small top heap according to the requirements of ascending and descending order;

  b. Swap the top element of the heap with the end element, and "sink" the largest element to the end of the array;

  c. Readjust the structure so that it satisfies the heap definition, and then continue to exchange the top element of the heap and the current end element, and repeat the adjustment + exchange steps until the entire sequence is in order.

 

 

Code

package facehandjava.sort;

public class HeapSort {
    public static void main(String[] args) {
        int[] arrays = {10, 5, 36, 78,56,2, 5, 8, 9, 9};

        int min = 0;
        int max = arrays.length-1;
        System.out.print("原来的:");
        for(int i =0;i<=max;i++) {
            System.out.print(arrays[i]+",");
        }
        System.out.println();
        HeapSort(arrays,max);
        System.out.print("排序后:");
        for(int i =0;i<=max;i++) {
            System.out.print(arrays[i]+",");
        }

    }

    public static void HeapSort(int[] arrays, int max) {
        //构造堆
        for (int i = max / 2 - 1; i >= 0; i--) {
            headAdjust(arrays, i, max);
        }
        // Swap the last one and rebuild the heap
         while (max >= 0 ) {
             swap (arrays, 0 , max);
            max--;
            headAdjust(arrays, 0, max);
        }

    }

    public static void headAdjust(int[] arrays, int i, int max) {

        int k ;
        int left;
        int right;
        while ((left= i * 2 + 1) <= max) {
            right = left + 1;
            k = left;
            //k<max , prove that there is right . If the right is large, the pointer points to the right.
            if (k < max && arrays[k] < arrays[right]) {
                k++;
            }
            // Father is smaller than child, swap. And i should point to the child, and make the next judgment. If there are still child nodes, continue to judge and exchange until i has no child nodes
             if (arrays[i] < arrays[k]) {
                 swap (arrays, i, k);
                i = k;
            } else {
                break;
            }
        }

    }

    public static void swap(int[] arrays,int a, int b) {
        int temp = arrays[a];
        arrays[a] = arrays[b];
        arrays[b] = temp;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325542016&siteId=291194637