Sort - Sort Heap (Heap sort)

background knowledge

What is the heap

Stack is complete binary tree data structure, a non-linear data structure . The stack can be seen as an array, can also be considered a complete binary tree, popular in terms of the heap in fact, is the use of complete binary tree structure to maintain a one-dimensional array .

Heap type

According to the characteristics of the stack can be divided into a large pile top and small top heap . As shown below.

Large stack top (max heap)

Keywords with a node (also known as top of the heap) is a pile of all the nodes in the largest of keywords, called the large root heap, also known as the maximum heap (heap big top).

Big Top heap requirements both keyword root key value equal to or greater than the left subtree, and greater than or equal to the key value of the right subtree. As shown in FIG.

Small top stack (min heap)

Keywords with a node (also known as top of the heap) are nodes pile all the keywords in the smallest, called small heap root, also known as the minimum heap (top small heap).

Top small heap requires both root keywords or less left subtree key value, and less than or equal to the key value of the right subtree. As shown in FIG.

Data structure descriptor

We use an array of nodes are numbered layers of the stack, with reference to the map data, map the logical structure of such an array will look like:

The array is logically a heap structure, we use a simple formula to describe the stack definition is:

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

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

Algorithm thinking

1, the collating sequence to be configured into a large pile top, at this time, the maximum value of the root node is the top of the stack of the entire sequence.

2, it will be exchanged with the last element on the end of this time the maximum value.

3, then the remaining elements of the n-1 reconstructed into a large pile top, it would receive the next smallest value of n elements.

4, so repeatedly executed, it will be able to get an ordered sequence of.

Graphic algorithm

Suppose we have a sequence {4, 6, 8, 5, 9}. As shown below.

Step one, the initial configuration of the stack.

Given sequence disorder configured to stack a large top (top stack with large ships ascending, descending a small stack top).

1, the sequence given disordered structure is shown below in FIG. Now we need to adjust to the big top disorderly heap heap.

2, the last time we start from a non-leaf node (leaf node NATURAL without adjustment, the first non-leaf node arr.length / 2-1 = 5 / 2-1 = 1, i.e. below junction 6 point), from left to right, from the bottom is adjusted. Adjustment process as shown in FIG.

3, to find a second non-leaf nodes 4, since [4,9,8] Maximum switching element 9, 9 and 4. Adjustment process as shown in FIG.

4, then, led to the exchange sub-root [4,5,6] chaotic structure, continue to adjust the [4,5,6] Maximum 6, 4 and 6 exchange.

At this point, we will construct a sequence without having to become a top big heap.

Step two, the top of the stack elements and switching elements at the end of

The top of the heap element and the last element to be exchanged, the end of the maximum element. Then continue to adjust the stack, then the top of the stack elements and switching elements at the end, to give a second large element. So again exchanged, rebuild, exchange.

1, the top of the stack element 9 and the end element 4 is exchanged. Exchange process as shown in FIG.

2, re-adjust the structure, so that it continues to meet the definition of the heap. Process as shown in FIG.

3, then the top of the stack and the end element 8 exchange element 5, to obtain a second large element 8. Process as shown in FIG.

4, the subsequent process continues to adjust the exchange, so repeatedly, so that eventually the entire ordered sequence. As shown below.

Animation shows

GIF images thanks to five minutes learning algorithm provides.

Algorithm performance

time complexity

O (nlogn) .

Space complexity

The (1) .

stability

Instability .

Code

C and C ++

void max_heapify(int arr[], int start, int end) {
    // 建立父结点和子节点
    int dad = start;
    int son = dad * 2 + 1;
    while (son <= end) { // 若子节点在范围內才做比较
        if (son + 1 <= end && arr[son] < arr[son + 1]) // 先比较两个子节点大小,选择最大的
                son++;
        if (arr[dad] > arr[son]) // 如果父结点大于子节点代表调整完毕,跳出函数
            return;
        else { // 否则交换父子内容再继续子节点和孙结点比较
            swap(arr[dad], arr[son]);
            dad = son;
            son = dad * 2 + 1;
        }
    }
}

void heap_sort(int arr[], int len) {
    // 初始化,i從最後一個父節點開始調整
    for (int i = len / 2 - 1; i >= 0; i--)
        max_heapify(arr, i, len - 1);
    // 先將第一個元素和已经排好的元素前一位做交換,再從新調整(刚调整的元素之前的元素),直到排序完毕
    for (int i = len - 1; i > 0; i--) {
        swap(arr[0], arr[i]);
        max_heapify(arr, 0, i - 1);
    }
}

Java

public class HeapSort implements IArraySort {
    @Override
    public int[] sort(int[] sourceArray) throws Exception {
        // 对 arr 进行拷贝,不改变参数内容
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        int len = arr.length;

        buildMaxHeap(arr, len);

        for (int i = len - 1; i > 0; i--) {
            swap(arr, 0, i);
            len--;
            heapify(arr, 0, len);
        }
        return arr;
    }

    private void buildMaxHeap(int[] arr, int len) {
        for (int i = (int) Math.floor(len / 2); i >= 0; i--) {
            heapify(arr, i, len);
        }
    }

    private void heapify(int[] arr, int i, int len) {
        int left = 2 * i + 1;
        int right = 2 * i + 2;
        int largest = i;

        if (left < len && arr[left] > arr[largest]) {
            largest = left;
        }

        if (right < len && arr[right] > arr[largest]) {
            largest = right;
        }

        if (largest != i) {
            swap(arr, i, largest);
            heapify(arr, largest, len);
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

Python

def buildMaxHeap(arr):
    import math
    for i in range(math.floor(len(arr)/2),-1,-1):
        heapify(arr,i)

def heapify(arr, i):
    left = 2*i+1
    right = 2*i+2
    largest = i
    if left < arrLen and arr[left] > arr[largest]:
        largest = left
    if right < arrLen and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        swap(arr, i, largest)
        heapify(arr, largest)

def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]

def heapSort(arr):
    global arrLen
    arrLen = len(arr)
    buildMaxHeap(arr)
    for i in range(len(arr)-1,0,-1):
        swap(arr,0,i)
        arrLen -=1
        heapify(arr, 0)
    return arr

 

Published 140 original articles · won praise 10 · views 470 000 +

Guess you like

Origin blog.csdn.net/justidle/article/details/104203969