"Data structure" sort of the pile, heap sort and its predecessor selection sort

Source: Internet
Author: User

Heap

Priority queue: A special "queue" in which the order in which elements are taken is based on the priority (keyword) size of the element, not the order in which the element enters the queue
The heap is a complete binary tree representation of the priority queue.
Two properties of the heap:
① Structure: A complete binary tree represented by an array
② ordering: The keyword of any node is the maximum value of all nodes of its subtree, called the maximum heap (or minimum, called the Minimum Heap) (note the order of the node sequence from the root node to any node path)

Here is an example of the largest heap.

/** Maximum heap operation * /typedef struct HEAPSTRUCT *maxheap;struct heapstruct {ElementType *elements;//array of storage heap elements    intSize;//Heap Size    intcapacity;//maximum capacity of the heap}; Maxheap Create (intMaxSize) {/** Creating the largest heap with capacity of maxsize * /Maxheap H = malloc (sizeof (struct heapstruct)); H->elements = malloc ((maxsize+1) *sizeof (ElementType)); H->size =0;    h->capacity = Maxheap; h->elements[0] = MaxData;/** Sentinel is greater than the value of all possible elements in the heap for later operation * /    returnH;}voidInsert (maxheap h,elementtype Item) {/** The element item into the maximum heap H * /    intIif(Isfull (H)) {printf ("Max Heap is full!\n");return; } i = ++h->size;//i points to the position of the last element in the post-insert heap     for( ; h->elements[i/2] > Item && i >1; I/=2) {H->elements[i] = h->elements[i/2];//Down filter node} H->elements[i] = Item;//Insert Item}elementtype Deletemax (maxheap H) {/** Remove the element with the largest key value from the Max Heap H and delete a node.    intParent,child; ElementType maxitem,temp;if(IsEmpty (H)) {printf ("Max heap empty!\n");return; } MaxItem = h->elements[1];//Remove root node max.    /** Filters The lower nodes up from the root node with the last element in the largest heap * /temp = h->elements[h->size--]; for(Parent =1; parent*2<= h->size; Parent = child) {child = parent*2;if((Child! = h->size) && (h->elements[child+1] (> H->elements[child])) child + +;//child pointing to the larger of the left and right sub-nodes        if(temp >= h->elements[child]) Break;ElseH->elements[parent] = h->elements[child];//Move the temp element to the next layer} H->elements[parent] = temp;returnMaxItem;}
Select Sort

The basic idea of choosing a sort (Selection sort) is that each trip selects the record with the lowest keyword in the n-i+1 (i=1,2,..., n-1) record as the first record in the ordered sequence.
Simple selection Sort: Nothing to say, the code is as follows

void SelectSort(SqList &L){    //对顺序表L作简单选择排序    for1 ; i < L.lenth ; ++i) {//选择第i小的记录,并交换到位        j = SelectMinKey(L,i);//选择最小的记录        if(i != j) swap(L[i],L[j]);//与第i个记录交换    }}//SelectSort

Tree selection Sort: can be replaced by heap sorting, so no longer detailed

Heap Sort

Let's look at a simple O (NLOGN) algorithm that uses heaps

void Heap_Sort(ElementType A[],int N){    BuildHeap(A);//建立最小堆    for0 ; i < N ; i ++)        TmpA[i] = DeleteMin(A);//取出堆中最小的元素并返回给TmpA    for0 ; i < N ; i ++)        A[i] = TmpA[i];//导回原数组}

The real heap sort is not to build the smallest heap, but to build the largest heap, each time root and the last element of the largest heap, and then maintaining it as the largest heap, until all is exchanged. The code is as follows

void Heap_Sort(ElementType A[],int N){    /** PercDown(A,a,b)表示在A中考虑前b-1个 把第a个元素下移到该在的位置 */    for(i = N/20 ; i --)        PercDown(A,i,N);//BuildHeap    for(i = N-10 ; i --) {        Swap(&A[0],&A[i]);//DeleteMax        PercDown(A,0,i);    }}

Here's a sort of experiment that will
int s[20] = {11,5,12,6,7,14,20,2,15,3,17,13,1,18,9,4,16,8,10,19};
This set of data is processed by simple selection sorting and heap sorting, which are repeated 10 million times respectively.
The results are as follows

If we add the data to 30:

This also shows that the heap ordering is efficient for big data (which is, of course, hypothetical).
Here is the experiment code:

#include <cstdio> #include <ctime>intMain () {intt =10000000;intstart = Clock (); while(t--) {ints[ -] = { -, One, in,5, A,6, +,7, at, -, -, A, -,2, the,3, -, -,1, -, -,9,4, -, -,8,Ten, -, +, -}; for(inti =0; I < in; i + +) {//Identify element I            intK,mi= to; for(intj = i; J < -; J + +) {if(Mi > S[j])                    {mi = s[j];                K = J; }            }if(i! = k) {intTMP = S[i];                S[i] = s[k];            S[K] = tmp; }        }    }/** Simple Selection sort * /    int_end = Clock (); printf"Simple select sort requires%dms\n", _end-start); t =10000000; start = Clock (); while(t--) {ints[ -] = { -, One, in,5, A,6, +,7, at, -, -, A, -,2, the,3, -, -,1, -, -,9,4, -, -,8,Ten, -, +, -}; for(inti = -; I >=0; I--) {/** S[i] Change to the location of the change * /            intpar = i; for(intChild =2*par+1; Child < -; Child =2*par+1) {if(Child! = in&& S[child] < s[child+1]) child++;if(S[par] >= S[child]) Break;Else{intTMP = S[par];                    S[par] = S[child];                S[child] = tmp;            } par = child; }        } for(inti = in; I >=1; I--) {intTMP = S[i]; S[i] = s[0]; s[0] = tmp;/** S[0] to the appropriate location consider the 0-(i-1) element */            intPar =0; for(intChild = par*2+1; Child < I; Child = par*2+1) {if(Child! = I1&& S[child] < s[child+1]) child++;if(S[par] >= S[child]) Break;Else{intTMP = S[par];                    S[par] = S[child];                S[child] = tmp;            } par = child; }        }    }/** Heap Sort * /_end = Clock (); printf"heap ordering requires%dms\n", _end-start);return 0;}

"Data structure" sort of the pile, heap sort and its predecessor selection sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.