Collection of Algorithm for sorting. Common Sorting Algorithm set (2)

Source: Internet
Author: User
Collection of Algorithm for sortingheap sort heap sorting

The heapsort algorithm can be divided into two parts.

In the first step, a heap is built out of the data. the heap is often placed in an array with the layout of a Complete Binary Tree. the Complete Binary Tree maps the binary tree structure into the array indices; each array index represents a node; the index of the node's parent, left Child Branch, or right Child Branch are simple expressions. for a zero-based array, the root node is stored at index 0; ifiIs the index of the current node, then

  iParent     = floor((i-1) / 2)  iLeftChild  = 2*i + 1  iRightChild = 2*i + 2

If one-base array is used, the root node is

Iparent = floor (I/2 );

Ileftchild = 2 * I;

Rightchild = 2 * I + 1;

I used the one-base method in code implementation.

In the second step, a sorted array is created by repeatedly removing the largest element from the heap (the root of the heap), and inserting it into the array. the heap is updated after each removal to maintain the heap. once all objects have been removed from the heap, the result is a sorted array.

Heapsort can be saved med in place. the array can be split into two parts, the sorted array and the heap. the storage of heaps as arrays is diagrammed here. the heap's invariant is preserved after each extraction, so the only cost is that of extraction.

 

Implementation of Heap Sort C language (because it is built on heap-ADT, "priority_queue.h" is implemented based on the previously implemented code of priority queue ")

Heap sorting is an interesting sorting ~

/***************************************************code writer:EOFcode file:heap_sort.ccode date:2014.09.19e-mail:[email protected]description:This is the kernel of the heap-sort.*****************************************************/#include "priority_queue.h"#define DEBUGint heap_sort(int* array,int size){struct heap* p_heap = NULL;p_heap = init_heap(size);if(!p_heap){printf("initialization failed in function %s() !\n",__FUNCTION__);return -1;}build_heap(p_heap,array,size);int tmp = 0;for(tmp = size;tmp > 0;tmp--){p_heap->element[tmp] = delete_heap(p_heap);}p_heap->size = size;#ifdef DEBUGfor(tmp = 1;tmp <=size;tmp++){printf("%4d",p_heap->element[tmp]);}printf("\n");#endifdestroy_heap(p_heap);return 0;}#ifdef DEBUGint main(){int array[] = {16,14,10,8,7,9,3,2,4,1};int size = sizeof(array)/sizeof(array[0]);heap_sort(array,size);return 0;}#endif


Test result (the smallest heap I used, so the sorting result is from large to small ):



Merge sort Merge Sorting


Algorithm analysis is not detailed. Just read "dsaa ".


It is worth mentioning that if a local temporary array is used for every recursive call of merge, the memory overhead will be very high during recursive calls, on the other hand, if you use the Merge function to call malloc internally to dynamically open up and release this array, it will take a lot of time. (I did not expect it later ~ Mark Allen Weiss's analysis is awesome ~)


For the above reason, open an array of size and the size of the array to be sorted outside merge, and then pass the pointer to the Merge function!


Merge_sort.h

#ifndef _MERGE_SORT_H#define _MERGE_SORT_H#include <stdio.h>#include <stdlib.h>int merge(int * array,int * tmp_array,int left_pos,int right_pos,int right_end);void msort(int *array,int * tmp_array,int left,int right);#endif


Merge. c

/************************************************************code writer:EOFcode date:2014.09.19code file:merge.c*************************************************************/#include "merge_sort.h"int merge(int * array,int * tmp_array,int left_pos,int right_pos,int right_end){if(!array || !tmp_array){printf("You passed NULL in function %s()\n",__FUNCTION__);return -1;}int tmp = 0;int tmp_pos= left_pos;int left_end = right_pos - 1;int num_element = right_end - left_pos + 1;/*It's too expensive to call malloc for costing time.int *tmp_array = NULL;tmp_array = (int *)malloc(sizeof(int)* num_element);if(!tmp_array){printf("malloc failed in function :%s()\n",__FUNCTION__);return 0;}*/while(left_pos <= left_end && right_pos <= right_end){if(array[left_pos] <= array[right_pos]){tmp_array[tmp_pos++] = array[left_pos++];}else{tmp_array[tmp_pos++] = array[right_pos++];}}while(left_pos <= left_end){tmp_array[tmp_pos++] = array[left_pos++];}while(right_pos <= right_end){tmp_array[tmp_pos++] = array[right_pos++];}for(tmp = 0;tmp < num_element;tmp++,right_end--){array[right_end] = tmp_array[right_end];}/*free(tmp_array);*/return 0;}

Msort. c

/************************************************************code writer:EOFcode date:2014.09.19code file:msort.c*************************************************************/#include "merge_sort.h"void msort(int *array,int * tmp_array,int left,int right){if(!array || !tmp_array){printf("You passed NULL in function %s()\n",__FUNCTION__);return ;}if(left > right){printf("left %d bigger than right %d\n",left,right);}int center = 0;/***When left == right, recursion end :)*/if(left < right){center = (left+right)/2;msort(array,tmp_array,left,center);msort(array,tmp_array,center+1,right);merge(array,tmp_array,left,center+1,right);}}

Test procedure:

Merge_sort_test.c

/************************************************************code writer:EOFcode date:2014.09.19code file:merge_sort_test.cdescription:Code for test function msort() :)*************************************************************/#include "merge_sort.h"int main(){int array[] = {10,12,1,14,6,5,8,15,3,9,7,4,11,13,2};int size = sizeof(array)/sizeof(array[0]);int tmp = 0;int *tmp_array = NULL;tmp_array = (int*) malloc(sizeof(int)*size);if(!tmp_array){printf("malloc failed in function %s()\n",__FUNCTION__);return 0;}msort(array,tmp_array,0,size-1);free(tmp_array);for(tmp = 0;tmp < size;tmp++){printf("%5d",array[tmp]);}printf("\n");return 0;}






Collection of Algorithm for sorting. Common Sorting Algorithm set (2)

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.