Source code of several sorting algorithms

Source: Internet
Author: User
Insert sort
Insertionsort. h
# Ifndef _ insertionsort_h_fe
# DEFINE _ insertionsort_h_fe // insert sorting
Void insertion_sort (int * a, int Len); # endif
Insertionsort. cpp
Void insert_item (int * a, int max_index, int item); // insert sorting
Void insertion_sort (int * a, int Len)
...{
For (INT I = 0; I <Len; I ++ )...{
Insert_item (A, I, a [I]);
}
} // Insert a new element into the sorted Array
// Sort in descending order
Void insert_item (int * a, int max_index, int item)
...{
Int I = 0; // move the element position greater than the value of the data to be inserted one by one
For (I = max_index-1; (I> = 0) & (item <A [I]); I --)...{
A [I + 1] = A [I];
} // Insert an element in the correct position
A [I + 1] = item;
} Merge and sort
Mergesort. h
# Ifndef _ mergesort_h_fe
# DEFINE _ mergesort_h_fe // merge and sort
Void merge_sort (int * a, int low, int high); // merge insert sort
Void merge_insertion_sort (int * a, int low, int high); // sort by static linked list Merging
Void merge_sort_link (int * a, int low, int high, int * link, Int & head); # endif
Mergesort. cpp
# Include <stdio. h>
# Include <stdlib. h> # include "insertionsort. H" Void Merge (int * a, int low, int middle, int high );
Void merge_link (int * a, int * link, Int & head, int H1, int H2); // merge and sort
Void merge_sort (int * a, int low, int high)
...{
Int middle = 0; // divides the array to be sorted into two groups and sorts them before merging.
If (low // The grouping policy is separated from the array.
Middle = (INT) (low + high)/2 );
// Recursively group and sort the first half
Merge_sort (A, low, middle );
// Recursive grouping and sorting of the second half
Merge_sort (A, middle + 1, high );
// Combine the first and last sorted items into the final sorted Array
Merge (A, low, middle, high );
}
} // Sort the merge Inserts
// Unlike the direct Merge Sorting, insert sorting is directly used when the array size is small to reduce the recursive overhead.
Void merge_insertion_sort (int * a, int low, int high)
...{
Int middle = 0; // USE insert sorting when the array size is small to a certain size (16) to avoid excessive recursive calls.
If (high-low + 1)> 16 )...{
// The grouping policy is separated from the array.
Middle = (INT) (low + high)/2 );
// Recursively group and sort the first half
Merge_sort (A, low, middle );
// Recursive grouping and sorting of the second half
Merge_sort (A, middle + 1, high );
// Combine the first and last sorted items into the final sorted Array
Merge (A, low, middle, high );
}
Else ...{
// Sort small arrays by insert
Insertion_sort (a + low), (high-low + 1 ));
}
} // Synthesize the sorted arrays of the first and second parts
Void Merge (int * a, int low, int middle, int high)
...{
Int * B = NULL;
// A1 points to the beginning of the first half of a sorted Array
// A2 points to the beginning of the sorted array in the second half of.
// BP points to the beginning of the temporary array B
Int a1 = low, a2 = middle + 1, BP = 0; // apply for space for the temporary array B, the size is high-low + 1
If (B = new int [High-low + 1]) = NULL )...{
Printf ("memory out .");
Exit (1 );
} // When there are elements in the last two groups, put them into B in the order of their size
// Until a group has no elements
While (A1 <= middle) & (A2 <= high ))...{
// If the first half of the Header element is smaller than the second half of the Header element
// Place the first half of the Header element in B, and the position variable increases progressively.
If (A [a1] <= A [a2])... {
B [BP ++] = A [a1 ++];
}
// Otherwise, add the Header element in the second half to B, and the position variable increases progressively.
Else ...{
B [BP ++] = A [A2 ++];
}
} // If the elements in the first half have been obtained, the remaining elements may exist in the second half.
If (A1> middle )...{
// Add the remaining elements in the second half to B at a time.
While (A2 <= high )...{
B [BP ++] = A [A2 ++];
}
}
// If the elements in the second half are finished, the first half may have element surplus.
Else if (A2> high )...{
// Add the remaining elements of the first half to B at a time.
While (A1 <= middle )...{
B [BP ++] = A [a1 ++];
}
} // Copy the elements in the temporary array B back to the corresponding position in
For (BP = 0; BP A [Low + bp] = B [BP];
} // Release temporary array B
If (B! = NULL )...{
Delete [] B;
}
} // Sort by static linked list
// Finally modify the head value to point it to the starting position of the array indicated by the static linked list
Void merge_sort_link (int * a, int low, int high, int * link, Int & head)
...{
Int middle = 0;
// H1 and H2 are the headers of the static linked list of sub-arrays.
// When recursive calls return, they point to the static linked list header of some arrays correctly
Int H1 = 0, H2 = 0; // merge two channels
If (low // Divide the array into two parts from the middle of the array, sort them separately, and then merge them.
Middle = (INT) (low + high)/2 );
// Call the Merge function recursively to obtain the static linked list header of the first half sub-array, and enter the value in the Link corresponding to the first half of the sub-array.
Merge_sort_link (A, low, middle, Link, H1 );
// Call the Merge function recursively to obtain the static linked list header of the second half sub-array, and enter the value in the Link corresponding to the second half sub-array.
Merge_sort_link (A, middle + 1, high, Link, H2 );
// Merge the static linked lists of the sorted arrays of the two parts, and correctly return the header of the static linked list corresponding to the merged Large Array
Merge_link (A, Link, Head, H1, H2 );
}
Else ...{
// When the sub-array has only one element, the head of the static linked list points to the element itself.
Head = low;
}
} // Merge the static linked list of two sub-arrays (modify the value of the static linked list), and return the header of the static linked list corresponding to the merged large array.
Void merge_link (int * a, int * link, Int & head, int H1, int H2)
...{
// Where, I and J point to the head of the static linked list of the two sub-arrays respectively.
// And constantly move back until a head points to the end of the Child Array
// K is the position written in the link of the current static linked list, which corresponds to the index of the last element currently retrieved in the array
Int I = h1, j = h2, K = 0; // first obtain the index of the first element of the merged large array, and point the head of the static linked list to this element.
If (A [I] <A [J])... {
Head = I;
K = I;
I = link [I];
}
Else ...{
Head = J;
K = J;
J = link [J];
} // Continuously removes elements from the two subarrays in size order based on the instructions of the static linked list of the two subarrays
// Until a child array is empty
While (I! =-1) & (J! =-1 ))...{
If (A [I] <A [J])... {
// Point the corresponding static linked list unit of the element's precursor element to the element
Link [k] = I;
// The next static linked list unit to be updated is the unit corresponding to the element currently removed
K = I;
// The Header element of the sub-array moves to the next element in the sub-array.
// The elements in the static linked list corresponding to the element index store the index of the subsequent element of the element.
I = link [I];
}
Else ...{
Link [k] = J;
K = J;
J = link [J];
}
} // After one of the two sub-arrays is empty
// Directly link the static linked list of the remaining elements of another sub-array to the static linked list unit corresponding to the last element.
If (I =-1 )...{
Link [k] = J;
}
Else ...{
Link [k] = I;
}
} Quick sorting
Quicksort. h
# Ifndef _ quicksort_h_fe
# DEFINE _ quicksort_h_fe // quick sorting
Void quick_sort (int * a, int left, int right); // sort by Quick insertion
Void quick_insertion_sort (int * a, int left, int right); # endif
Quicksort. cpp
# Include "insertionsort. H" int sel_pivot (int * a, int left, int right );
Void swap (int * a, int I, Int J );
Void partition (int * a, int left, Int & effect_pos); // fast sorting
Void quick_sort (int * a, int left, int right)
...{
// Central element location
Int effect_pos = 0;

If (left <right )...{
// Select the central element from the array to be sorted
Effect_pos = sel_pos (A, left, right );
// Swap the central element with the last element of the array, that is, place the central element at the end of the array
If (effect_pos! = Right )...{
Swap (A, effect_pos, right );
Effect_pos = right;
}
// Partition the Array Based on the selected central element, and return the location of the central element after the partition
Partition (A, left, effect_pos );
// Sort the arrays in the front of the central element recursively.
Quick_sort (A, left, effect_pos-1 );
// Perform quick sorting on the array recursion of the back part of the central element
Quick_sort (A, effect_pos + 1, right );
}
} // Fast insert sorting
// Unlike Direct Fast sorting, insert sorting is directly used when the array size is small to reduce recursive overhead.
Void quick_insertion_sort (int * a, int left, int right)
...{
Int effect_pos = 0; // USE insert sorting when the array size is smaller than or equal to 10
If (right-left + 1) <= 10 )...{
Insertion_sort (a + left), (right-left + 1 ));
}
Else ...{
Effect_pos = sel_pos (A, left, right );
If (effect_pos! = Right )...{
Swap (A, effect_pos, right );
Effect_pos = right;
}
Partition (A, left, effect_pos );
Quick_insertion_sort (A, left, effect_pos-1 );
Quick_insertion_sort (A, effect_pos + 1, right );
}
} // Select the central element from the array to be sorted, and return the position of the central element in the original array.
// The selected rule is to select the values between the header, tail, and intermediate elements of the array.
Int sel_rectangle (int * a, int left, int right)
...{
Int middle = (INT) (left + right)/2 );
Int temp [3] =... {A [left], a [Middle], a [right]}; insertion_sort (temp, 3); If (temp [1] = A [left])... {
Return left;
}
Else if (temp [1] = A [Middle])... {
Return middle;
}
Else ...{
Return right;
}
} // Exchange two elements in the array
Void swap (int * a, int I, Int J)
...{
// When two elements are the same element, they do not have to or cannot be exchanged in an exclusive or way.
// Otherwise, the element value will become zero.
If (I! = J )...{
A [I] ^ = A [J];
A [J] ^ = A [I];
A [I] ^ = A [J];
}
} // Partition Algorithm
// Divide the array into two groups based on the selected central element value
// The values of sub-array elements before the central element are smaller than or equal to the central element
// The Sub-array element values after the central element are greater than or equal to the central element
Void partition (int * a, int left, Int & effect_pos)
...{
Int I = left, j = effect_pos-1;
Int effect_val = A [effect_pos]; do ...{
// I queries from left to right until an element greater than or equal to the central element stops.
While (A [I] <effect_val )...{
I ++;
}
// J searches from right to left until an element smaller than or equal to the central element stops.
While (A [J]> effect_val )...{
J --;
} // Switch the element whose I points to greater than or equal to the central element and the element whose J points to smaller than or equal to the central element
// Because I points to the element on the left, and J points to the element on the right
// Put all elements less than or equal to the central element to the left of the array, and all elements greater than or equal to the central element to the right of the array
// The precondition for switching is that the I pointer is still on the left of the J pointer, that is, I <j, that is, the complete array has not been queried.
If (I <j )...{
Swap (A, I, j );
I ++;
J --;
}
} While (I <j); // when I is on the right of J, the loop ends, I points to the first element in the array that is equal to or greater than the central element // exchange the central element with the first element in the array that is greater than or equal to the central element
// Place the central element in the middle of the array
// All array elements on the left of the central element are smaller than or equal to the central element
// All array elements on the right of the central element are greater than or equal to the central element
Swap (A, I, effect_pos );
// Update the position pointer of the central element
Effect_pos = I;
} Use a test program to test the Merge Sorting, use the static linked list's Merge Sorting, fast sorting, and improve the efficiency of quick sorting.
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
# Include <windows. h> # include "mergesort. H"
# Include "quicksort. H" // number of groups with the same random array to be sorted
// Several groups of identical random arrays to be sorted are used to test the efficiency difference between different sorting algorithms.
# Define array_group_num 5
# Define round_num 6 void print_array (int * a, int Len );
Void print_array_link (int * a, int * link, int head, int endflag); int main (void)
...{
// The pointer array is used to point to several groups of sorted arrays with the same data.
Int * arr [array_group_num] =... {null };
// The length of each group of data
Int Len = 0;
// Used for timing, in milliseconds
DWORD tick_count = 0;
// Array static linked list, used to sort by static linked list Merging
Int * arr_link = NULL;
// Head Position of the static linked list
Int arr_link_head = 0; srand (unsigned INT) Time (null); Len = 1000; // perform a round_num round test in total, and the size of each round of array is increased by five times, initial scale: 1000
For (INT round = 0; Round <round_num; Round ++)... {// dynamically allocates space for each array
For (INT I = 0; I <array_group_num; I ++ )...{
If (ARR [I] = new int [Len]) = NULL )...{
Printf ("memory out .");
Return 1;
}
} // Allocate space for the static linked list. The size is the same as that of the array element.
If (arr_link = new int [Len]) = NULL )...{
Printf ("memory out .");
Return 1;
} // Assign the same random element value to each array for sorting
For (INT I = 0; I <Len; I ++ )...{
For (Int J = 0; j <array_group_num; j ++ )...{
Arr [J] [I] = rand ();
}
// Initialize the static linked list.-1 indicates pointing to null (because the array element starts from scratch, it cannot be pointed to null with zero)
Arr_link [I] =-1;
} // The efficiency comparison of various sorting algorithms is as follows:
// The first is normal Merge Sorting.
Printf ("sorting % d numbers with merge_sort...", Len );
Tick_count =: gettickcount ();
Merge_sort (ARR [0], 0, len-1 );
Tick_count =: gettickcount ()-tick_count;
Printf ("Total time: % d MS", tick_count );

// Use the merge sort of insert sort when the array is smaller than a certain size
Printf ("sorting % d numbers with merge_insertion_sort...", Len );
Tick_count =: gettickcount ();
Merge_insertion_sort (ARR [1], 0, len-1 );
Tick_count =: gettickcount ()-tick_count;
Printf ("Total time: % d MS", tick_count); // sort by static linked list
Printf ("sorting % d numbers with merge_sort_link...", Len );
Tick_count =: gettickcount ();
Merge_sort_link (ARR [2], 0, len-1, arr_link, arr_link_head );
Tick_count =: gettickcount ()-tick_count;
Printf ("Total time: % d MS", tick_count); // normal fast sorting
Printf ("sorting % d numbers with quick_sort...", Len );
Tick_count =: gettickcount ();
Quick_sort (ARR [3], 0, len-1 );
Tick_count =: gettickcount ()-tick_count;
Printf ("Total time: % d MS", tick_count); // USE insert-sorted quick sorting when the array is smaller than a certain size
Printf ("sorting % d numbers with quick_insertion_sort...", Len );
Tick_count =: gettickcount ();
Quick_insertion_sort (ARR [4], 0, len-1 );
Tick_count =: gettickcount ()-tick_count;
Printf ("Total time: % d MS", tick_count); // release the space of the applied temporary storage array
For (INT I = 0; I <array_group_num; I ++ )...{
If (ARR [I]! = NULL )...{
Delete [] arr [I];
}
} // Release the space of the temporary static linked list applied
If (arr_link! = NULL )...{
Delete [] arr_link;
} // The size of each round of array is increased by five times.
Len * = 5;
} System ("pause"); Return 0;
} // Print the array value
Void print_array (int * a, int Len)
...{
For (INT I = 0; I <Len; I ++ )...{
Printf ("% d", a [I]);
}
Printf ("");
} // Print the array in the order pointed by the static linked list
Void print_array_link (int * a, int * link, int head, int endflag)
...{
Int I = head; while (I! = Endflag )...{
Printf ("% d", a [I]);
I = link [I];
}
Printf ("");
}

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.