Analysis and Implementation of several common internal sorting algorithms (in C language)

Source: Internet
Author: User

<Analysis and implementation of several common internal sorting algorithms (in C Language)>
Tags: alg, c, blog, book, linux

1. Insert sorting

1.1 algorithm ideas

The main idea of inserting sorting algorithms is:

1) The sequence to be sorted is divided into two parts: sorted part (A) and unsorted part (B ).
The sorting part is separated by display positions. We can also call the sorted part as the first part of the sequence.
The sorting part is called the back part of the sequence. Obviously, before the algorithm starts, the sorted part is empty, and the unsorted part is
The entire sequence to be sorted.
2) Fetch the first element (B) from B, and then compare the elements (A) with B from the back to the front. If B <
A moves a position backward. Otherwise, B is found in the correct position (the next position of a) and B is placed in
This location (remember: A is sorted ).
3) add an element "B" to "A", and then remove an element "B" to "B.
4) Repeat steps 2-3 until B is empty.

1.2 Implementation

// # C ---/* ====================================== ========================================================== = ** @ description: * insert and sort ** @ Param base * @ Param nmemb * @ Param size * @ Param COMPAR * ================== ========================================================== =================== */void sort_insertsort (void * base, size_t nmemb, size_t size, INT (* COMPAR) (const void *, const void *) {# define swap (a, B, T) (t) = (A), (a) = (B), (B) = (t) assert (B ASE! = NULL & nmemb> = 1 & size> = 1 & COMPAR! = NULL); char * I, * j, T, * B, * E; char * bot = (char *) base; char * Top = bot + nmemb * size; for (I = bot + size; I <top; I + = size) {for (j = I; (j-= size)> = bot & COMPAR (I, j) <0;) {} if (I! = (J + = size) {for (B = J, E = I-1; B <E; B ++, e --) Swap (* B, * E, t); For (B = I, E = I + size-1; B <E; B ++, e --) Swap (* B, * E, T ); for (B = J, E = I + size-1; B <E; B ++, e --) Swap (* B, * E, T );}} # UNDEF swap} // # C --- end

1.3 algorithm complexity analysis

From the algorithm idea of inserting sorting, we can easily find that the spatial complexity is O (1), and the time complexity is O (N ^ 2 ).

2. Select sort

2.1 algorithm ideas

The main idea of selecting sorting algorithms is:

1) The sequence to be sorted is divided into two parts: sorted part (A) and unsorted part (B ).
The sorting part is separated by display positions. We can also call the sorted part as the first part of the sequence.
The sorting part is called the back part of the sequence. Obviously, before the algorithm starts, the sorted part is empty, and the unsorted part is an integer.
To be sorted.

2) traverse every element in B, find the smallest element (B) in B, and exchange the element after B and.

3) add an element "B" to "A", and then remove an element "B" to "B.

4) Repeat steps 2-3 until B is empty.

2.2 Implementation

// # C ---/* ====================================== ========================================================== = ** @ Description: * select ** @ Param base * @ Param nmemb * @ Param size * @ Param compar ** ============== ========================================================== ===================== */void Sort_selectSort (void * base, size_t nmemb, size_t size, int (* compar) (const void *, const void *) {# define SWAP (a, B, t) (t) = (a), (a) = (B), (B) = (t) assert ( Base! = NULL & nmemb> = 1 & size> = 1 & compar! = NULL); int s; char t, * I, * j, * min; char * left = base; char * right = left + (nmemb-1) * size; for (I = left; I <= right-size; I + = size) {min = I; for (j = I + size; j <= right; j + = size) {if (compar (j, min) <0) min = j;} if (I! = Min) for (s = 0; s <size; s ++) SWAP (* (I + s), * (min + s), t );} # undef SWAP} // # c --- end

2.3 algorithm complexity analysis

Select the space complexity of sorting as O (1) and time complexity as O (N ^ 2 ).

3. Bubble Sorting

3.1 algorithm ideas

The main idea of the Bubble Sorting Algorithm is:

1) The sequence to be sorted is divided into two parts: sorted part (A) and unsorted part (B ).
The sorted parts are separated by display positions. We can also call the sorted parts as the first part of the sequence and unsorted
This part is called the back part of the sequence. Obviously, before the algorithm starts, the sorted part is empty, and the unsorted part is the whole
The sequence to be sorted.

2) traverse B from the back to the front, and take all the adjacent two elements (b1 and b2, b1 are relatively back, b2 is relatively front) for comparison
If b1 <b2, then b1 and b2. after traversing all the elements of B, the first element (B) in B is placed
To the correct position.

3) add an element "B" to "A", and then remove an element "B" to "B.

4) Repeat steps 2-3 until B is empty.

3.2 Implementation

// # C ---/* ====================================== ========================================================== = ** @ description: * Bubble Sorting ** @ Param base * @ Param nmemb * @ Param size * @ Param COMPAR ** ============== ========================================================== ===================== */void sort_bubblesort (void * base, size_t nmemb, size_t size, INT (* COMPAR) (const void *, const void *) {# define swap (a, B, T) (t) = (A), (a) = (B), (B) = (t) assert (Base! = NULL & nmemb> = 1 & size> = 1 & COMPAR! = NULL); int S, isswap; char T, * I, * j; char * Left = base; char * Right = base + (nmemb-1) * size; for (I = left; I <right; I + = size) {isswap = 0; For (j = right; j> I; j-= size) {If (COMPAR (J, J-size) <0) {isswap = 1; for (S = 0; S <size; s ++) swap (* (J + S), * (J-size + S), t) ;}} if (isswap = 0) break ;} # UNDEF swap} // # C --- end

3.3 algorithm complexity analysis

The spatial complexity of Bubble Sorting is O (1), and the time complexity is O (N ^ 2 ).

4. Merge and sort

4.1 algorithm ideas

1) divide the sequence into two subsequences.

2) Merge and sort two subsequences recursively.

3) Merge the two subsequences (sorted) into an ordered sequence.

4.2 Implementation

// # C ---/* ====================================== ========================================================== = ** @ Description: * merging and sorting routines ** @ Param left * @ Param center * @ Param right * @ Param size * @ Param compar * @ Param tmparray ** ====== ========================================================== =========================*/static void SortST_memge (char * left, char * center, char * right, int size, int (* compar) (const void *, const void * ), Char * tmparray) {# define COPY_SIZE (d, s) \ do {\ for (I = 0; I <size; I ++) \ * (d) + I) = * (s) + I); \} while (0) int I; char * Lright = center; char * Rright = right; char * Lpcur = left; char * Rpcur = center + size; char * Tpcur = tmparray; for (; Lpcur <= Lright & Rpcur <= Rright; Tpcur + = size) {if (compar (Lpcur, rpcur) <0) {COPY_SIZE (Tpcur, Lpcur); Lpcur + = size;} else {COPY_S IZE (Tpcur, Rpcur); Rpcur + = size ;}for (; Lpcur <= Lright; Lpcur + = size, Tpcur + = size) COPY_SIZE (Tpcur, Lpcur ); for (; Rpcur <= Rright; Rpcur + = size, Tpcur + = size) COPY_SIZE (Tpcur, Rpcur); for (Lpcur = left; Lpcur <= right; lpcur + = size, tmparray + = size) COPY_SIZE (Lpcur, tmparray ); # undef COPY_SIZE}/* ==================================== ========================================================== ** @ Descr Iption: * merge and sort ** @ Param left * @ Param right * @ Param size * @ Param compar * @ Param tmparray ** ============== ========================================================== =============================== */static void Sort_mergeSort_priv (char * left, char * right, int size, int (* compar) (const void *, const void *), char * tmparray) {if (left <right) {char * center = left + (right-left)/size/2) * size; Sort_mergeSort_priv (l Eft, center, size, compar, tmparray); Sort_mergeSort_priv (center + size, right, size, compar, tmparray); SortST_memge (left, center, right, size, compar, tmparray );}} /* ===================================================== =================================================================** @ Description: * merge sort driver routine ** @ Param base * @ Param nmemb * @ Param size * @ Param compar ** ============== ========================================================== ============ ========= */Void Sort_mergeSort (void * base, size_t nmemb, size_t size, int (* compar) (const void *, const void *)) {assert (base! = NULL & nmemb> = 1 & size> = 1 & compar! = NULL); char * left = base; char * right = base + (nmemb-1) * size; char * tmparray; tmparray = malloc (nmemb * size ); if (tmparray = NULL) return; Sort_mergeSort_priv (left, right, size, compar, tmparray); free (tmparray);} // # c --- end


4.3 algorithm complexity analysis

The Merge Sorting Algorithm is an example of the use of the division idea. Its spatial complexity is O (N), and the time complexity is O (NlogN ).

5. Quick sorting

5.1 algorithm ideas

1) select any element (k) from the input sequence as the pivot element;

2) traverse the entire sequence. Put the elements smaller than or equal to k on the left (L) and those greater than k on the right (R );

3) perform recursive sorting on subsequences L and R until there is only one element in the sequence and exit recursion.

5.2 Implementation

// # C ---/* ====================================== ========================================================== = ** @ Description: * Take the median between the three parameters ** @ Param left * @ Param right * @ Param size * @ Param compar ** @ Returns: * ===================================================== ====================================================== */static char * sort_median3 (char * left, char * right, int size, int (* compar) (const void *, const void *) {# define SWAP (a, B, t) (t) = (a), (a) = (B ),( B) = (t) int s; char t; // char * center = left + (right-left)/2; // error !! // Every step of computing must be rounded up! In bytes! Char * center = left + (right-left)/size)/2) * size; if (compar (left, center)> 0) for (s = 0; s <size; s ++) SWAP (* (left + s), * (center + s), t); if (compar (left, right)> 0) for (s = 0; s <size; s ++) SWAP (* (left + s), * (right + s), t); if (compar (center, right)> 0) for (s = 0; s <size; s ++) SWAP (* (center + s), * (right + s), t ); for (s = 0; s <size; s ++) SWAP (* (center + s), * (right-siz E + s), t); return right-size; # undef SWAP}/* ====================================== ========================================================== ** @ Description: * fast sorting ** @ Param left * @ Param right * @ Param size * @ Param compar * ================ ========================================================== =================== */static void Sort_quicklySort_priv (char * left, char * right, int size, int (* compar) (const void *, const void *) {# define SWAP (, B, t) (t) = (a), (a) = (B), (B) = (t) int s; char t, * I, * j, * centers; if (left + SORT_CUTOFF * size <= right) {centers = Sort_median3 (left, right, size, compar); I = left; j = right-size; for (;) {for (I + = size; compar (I, bytes) <0; I + = size) {} for (j-= size; compar (j, rows)> 0; j-= size) {} if (I <j) {for (s = 0; s <size; s ++) SWAP (* (I + s), * (j + s), t);} else break;} (S = 0; s <size; s ++) SWAP (* (I + s), * (right-size + s), t); Sort_quicklySort_priv (left, i-size, size, compar); Sort_quicklySort_priv (I + size, right, size, compar);} else Sort_insertSort (left, (right-left)/size + 1, size, compar ); # undef SWAP}/* ====================================== ========================================================== ** @ Description: * fast sort driver routine ** @ Param base * @ Param nmemb * @ Param size * @ Param com Par * = ============================================ */void Sort_quicklySort (void * base, size_t nmemb, size_t size, int (* compar) (const void *, const void *) {assert (base! = NULL & nmemb> = 1 & size> = 1 & compar! = NULL); if (nmemb <= 1) return; if (nmemb> = SORT_CUTOFF) Sort_quicklySort_priv (base, base + (nmemb-1) * size, size, compar ); else Sort_insertSort (base, nmemb, size, compar);} // # c --- end

5.3 algorithm complexity analysis

The fast sorting algorithm also uses the Division idea. Its spatial complexity is O (1), and the time complexity is O (NlogN ).


Related Article

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.