Logical Structure: recursive Stack
Physical Structure: Array
Merge Sort Analysis:
Optimal Time Complexity: O (N)
Worst time complexity: O (nlog2n)
Average time complexity: O (nlog2n)
Worst space complexity: O (N)
Stability: Stability
Merge Sorting mainly has two functions:
1. Merge and sort int mergearray (int * list1, int list1_size, int * list2, int list2_size );
2 recursive Merge Sorting int mergesort (int * List, int list_size );
3 Non-recursive Merge Sorting int mergesort (int * List, int list_size );
// One-time Merge Sorting int mergearray (int * list1, int list1_size, int * list2, int list2_size) {int I, J, K, A; I = J = k = 0; int * List = (int *) malloc (sizeof (INT) * (listparts size + list2_size); While (I <listparts size & J <list2_size) {If (* (list1 + I) <= * (list2 + J) {* (list + k) = * (list1 + I); I ++; k ++;} else {* (list + k) = * (list2 + J); j ++; k ++ ;}} while (I <listparts size) {* (list + k) = * (list1 + I); I ++; k ++;} while (j <list2_size) {* (list + k) = * (list2 + J); j ++; k ++;} for (a = 0; A <(listparts size + list2_size); A ++) * (list1 + a) = * (list + a); free (list );}
// Recursive Merge Sorting int mergesort (int * List, int list_size) {If (list_size> 1) {int * list1 = List; int list1_size = list_size/2; int * list2 = List + list_size/2; int list2_size = list_size-list1_size; mergesort (list1, list1_size); mergesort (list2, list2_size); mergearray (list1, list1_size, list2, list2_size );}}
// Non-recursive Merge Sorting int nonmergesort (int * List, int list_size) {int I, l_min, l_max, r_min, r_max, cursor; int * aux = (int *) malloc (sizeof (INT) * list_size); for (I = 1; I <list_size; I * = 2) {for (l_min = 0; l_min <list_size-I; l_min = r_max) {r_min = l_max = l_min + I; r_max = l_max + I; If (r_max> list_size) r_max = list_size; cursor = 0; while (l_min <l_max & r_min <r_max) {If (list [l_min] <= list [r_min]) {aux [cursor ++] = list [l_min ++];} else {aux [cursor ++] = list [r_min ++];} while (l_min <l_max) aux [cursor ++] = list [l_min ++]; while (r_min <r_max) Aux [cursor ++] = list [r_min ++]; while (cursor> 0) list [-- r_min] = aux [-- cursor] ;}} free (Aux );}
// Non-recursive Merge Sorting int nonmergesort1 (int * List, int length) {int I, left_min, left_max, right_min, right_max, next; int * TMP = (int *) malloc (sizeof (INT) * length); If (TMP = NULL) {fputs ("error: out of memory \ n", stderr); abort ();} for (I = 1; I <length; I * = 2) {for (left_min = 0; left_min <length-I; left_min = right_max) {right_min = left_max = left_min + I; right_max = left_max + I; If (right_max > Length) right_max = length; next = 0; while (left_min <left_max & right_min <right_max) TMP [next ++] = list [left_min]> list [right_min]? List [right_min ++]: list [left_min ++]; while (left_min <left_max) list [-- right_min] = list [-- left_max]; while (next> 0) list [-- right_min] = TMP [-- next] ;}} free (TMP );}
Consolidate the foundation -- merge and sort