C examples for Data Structure:Sort
Merge Sort Array
#include <stdio.h> #define MaxSize 20//from w ww . j a v a 2 s . c om void mergeSort(int[], int, int); int main() { int num[] = { 41,82,63,146,51,69,714,82,93,05,118,213,317,47,152,161,175,190 }; int n = 18; mergeSort(num, 0, n - 1); for (int h = 0; h < n; h++) printf("%d ", num[h]); printf("\n\n"); return 0; } void mergeSort(int A[], int lo, int hi) { void merge(int[], int, int, int); if (lo < hi) { //list contains at least 2 elements int mid = (lo + hi) / 2; //get the mid-point subscript mergeSort(A, lo, mid); //sort first half mergeSort(A, mid + 1, hi); //sort second half merge(A, lo, mid, hi); //merge sorted halves } } void merge(int A[], int lo, int mid, int hi) { int T[MaxSize]; int i = lo; int j = mid + 1; int k = lo; while (i <= mid || j <= hi) { if (i > mid) T[k++] = A[j++]; else if (j > hi) T[k++] = A[i++]; else if (A[i] < A[j]) T[k++] = A[i++]; else T[k++] = A[j++]; } for (j = lo; j <= hi; j++) A[j] = T[j]; }