[Sort] sorting by Sorting Algorithm

Source: Internet
Author: User

SortAlgorithmSort by selection

Luo chaohui (http://www.cnblogs.com/kesalin) This article follows the "signature-non-commercial use-consistency" creation public agreement


Sorting is an important operation frequently used in data processing. In computers and their application systems, the time spent on Sorting occupies a large proportion in the system running time. The importance of sorting does not need to be repeated. The following describes the common sorting methods for simple analysis and comparison, and provides the C language implementation.

 

The so-called sorting means to sort a bunch of records in ascending (or descending) Order of keywords. The sorting rules can be divided into the following five types:

1. Insert sorting (insert sorting directly and sort by Hill );

2. Exchange sorting (Bubble sorting and quick sorting );

3. Select sorting (directly select sorting and heap sorting );

4. Merge and sort;

5. Sort buckets (bucket sorting and base sorting );

 

---------------------------------------------------------------------------------

 

We talked about insert and exchange sorting. Next we will talk about selecting sorting.

The basic idea of selection sort is: each trip selects the records with the smallest keyword from the records to be sorted, and puts the order at the end of the sorted subfile, until all records are sorted.

Common sorting methods include direct sorting and heap sorting.

 

Select sort directly

Basic Idea: divides the records to be sorted into ordered and unordered areas. In the initial state, the ordered location is empty, and the unordered area is the entire record to be sorted. Sorting is to select the smallest (or largest) record in the unordered area and insert it to the end of the ordered area. The sorting is completed until the unordered area is empty.

 

CodeImplementation

 //  Select sort directly
//
Void Select_sort ( Int * Array, Int Length)
{
Assert (array & length> =0 );

Int I, J, K, temp;

For (I = 0 ; I <length- 1 ; ++ I ){
K = I;

For (J = I + 1 ; J <length; ++ J ){
If (Array [J] <array [k]) {
K = J;
}
}

If (K! = I ){
Temp = array [I];
Array [I] = array [k];
Array [k] = temp;
}
}
}

 

Time Complexity Analysis:

Regardless of the initial status of the record to be sorted, n-I comparisons are required to select the record with the minimum keyword in the I-th sorting. Therefore, the total number of comparisons is: N * (N-1)/2 = O (N ^ 2). When the initial status of the record to be sorted is positive, the number of moves is 0. When the initial status is backward, exchange is performed for each sort. the maximum number of moves is 3*(n-1 ). Therefore, the average time complexity of sorting is O (n ^ 2 ).

 

Spatial complexity:

Obviously, O (1 ).

 

Supplement:

Direct sorting is a local sorting and non-stable sorting.

 

Heap sorting

stack definition: the series of N keywords that meet the following constraints: k L , k 2 ,..., K n is called a heap, 1 ≤ I ≤ n/2,
(1) k I ≤ k 2I and K I ≤ k 2I + 1 (small root heap) or

(2) kI≥ K2IAnd KI≥ K2I + 1 (large heap)


From the perspective of definition, heap is essentially a Complete Binary Tree that meets the following requirements: the keywords of any non-leaf node in the tree are not greater than (or less than) their left and right children (if any) node keyword. Heap sorting is to make full use of the heap top record, which is either the largest or the smallest ordered property. Each time you select the maximum or minimum keyword in the heap to complete the sorting. Heap sorting is also a kind of sorting method, which is more efficient than the average efficiency of directly selecting sorting, because the comparison results are not saved after each comparison, as a result, duplicate comparisons may exist, the heap uses its heap nature to store the comparison results in the heap (the children on the left of non-leaf nodes must not be greater than or less than the children on the right ).


The key to heap sorting is to create a pile of records to be sorted. After the heap is created, record the heap top of the unordered area (always the largest or smallest unordered area) exchange with the last record of the unordered area. After the exchange, the last record of the unordered area becomes the first record of the ordered area. The New Record of the unordered area does not necessarily meet the heap nature, therefore, the unordered zone must be adjusted and heap. This loop ends until the unordered area is empty.


The main steps of heap sorting are as follows:

1. Create an initial heap;

2. Swap unordered top record with the last record to narrow down the unordered area;

3. Change the unordered partition after the switch to heap and repeat Step 2.


Code implementation:

 //  The stacking method adjusts the heap. Except for [low], the two children of [low] are already large.  
Void Adjust_heap ( Int * Heap, Int Low, Int High)
{
Assert (HEAP );

# If 1 // Loop implementation

Int I = low;
Int J = 2 * I;
Int Temp = heap [I];

While (J <= high ){
// If two children exist, J is the subscript of the largest child.
If (J <High & heap [J] 1 ]) {
J = J + 1 ;
}

// Already heap
If (Temp> = heap [J]) {
Break ;
}

// Continue Filtering
Else {
Heap [I] = heap [J];
I = J;
J = 2 * I;
}
}

Heap [I] = temp;

# Else // Recursive Implementation

Int I = low;
Int J = 2 * I;
Int Temp = heap [I];

If (J> = high ){
Return ;
}

// If two children exist, J is the subscript of the largest child.
If (J <High & heap [J + 1 ]> Heap [J]) {
J = J + 1 ;
}

// It is already a heap and does not need to be adjusted
If (Heap [low]> = heap [J]) {
Return ;
}

Heap [I] = heap [J];
Heap [J] = temp;

// After adjustment, [J, high] may not be able to meet the heap requirement. You need to continue the adjustment.
Adjust_heap (heap, J, high );

# Endif
}

// A tree with only one node is a heap, and in a Complete Binary Tree, all nodes with the serial number I> n/2 are leaves,
// Therefore, the subtree rooted in these nodes is already heap. In this way, we only need
// N/2, n/2-1 ,..., Zero node as the root subtree can be adjusted to heap.
Void Build_heap ( Int * Heap, Int Length)
{
Assert (heap & length> = 0 );

Int I;

For (I = length/ 2 ; I> = 0 ; -- I ){
Adjust_heap (heap, I, length- 1 );
}
}


// Heap sorting
//
Void Heap_sort ( Int * Array, Int Length)
{
Assert (array & length> = 0 );

If (Length <= 1 ){
Return ;
}

Int I, temp;

// Build [0, length-1] into the initial heap
Build_heap (array, length );

// [0, I-1] of the unordered area is sorted by heap, And the length-1 trip is performed in total.
For (I = length- 1 ; I> 0 ; -- I ){
// Swap the last record in the heap and heap
Temp = array [ 0 ];
Array [ 0 ] = Array [I];
Array [I] = temp;

// Change [0, I-1] to heap. Only [0] may violate the heap nature.
Adjust_heap (array, 0 , I- 1 );
}
}


Time Complexity Analysis:

The time overhead of heap sorting mainly consists of the time overhead of establishing the initial heap and adjusting the heap repeatedly. You can think of it as a binary tree. The average time complexity of heap sorting is O (nlgn ).

 

Spatial complexity analysis:

Obviously, it is O (1 ).


Supplement:

Heap sorting is an unstable local sorting.


========================================================== ========================================================== ========

Test:

Add two lines of code based on the preceding "insert sort by sorting algorithm" test code:

 

Sortfucntioninfo sort_function_list [] = {

{"Select sort directly", select_sort },

{"Heap_sort", heap_sort },

{"", Null}

};

 

Running result:

 

=== Select sort directly ===

Original: 65 32 49 10 8 72 27 42 18 58 91

Sorted: 8 10 18 27 32 42 49 58 65 72 91

 

Original: 10 9 8 7 6 5 4 3 2 1 0

Sorted: 10 0 1 2 3 4 5 6 7 8 9

 

=== Heap sorting ===

Original: 65 32 49 10 8 72 27 42 18 58 91

Sorted: 8 10 18 27 32 42 49 58 65 72 91

 

Original: 10 9 8 7 6 5 4 3 2 1 0

Sorted: 0 1 2 3 4 5 6 7 8 9 10

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.