Sort a Given List of Numbers Using a Merge Sort - C Data Structure

C examples for Data Structure:Sort

Description

Sort a Given List of Numbers Using a Merge Sort

Demo Code

#include<stdio.h>

int myArray[20];/*from   ww w .j  a va2  s .c om*/
int count = 10;

void merge(int m1, int n1, int m2, int n2);

void mergeSort(int m, int n)
{
    int intMid;
    if(m < n)
    {
        intMid = (m + n)/2;
        mergeSort(m, intMid);
        mergeSort(intMid + 1, n);
        merge(m, intMid, intMid + 1, n);
    }
}

void merge(int m1, int n1, int m2, int n2)
{
    int tmpStorage[40];
    int m, n, k;
    m = m1;
    n = m2;
    k = 0;
    while(m <= n1 && n <= n2)
    {
        if(myArray[m] < myArray[n])
            tmpStorage[k++] = myArray[m++];
        else
            tmpStorage[k++] = myArray[n++];
    }
    while(m <= n1)
        tmpStorage[k++] = myArray[m++];
    while(n <= n2)
        tmpStorage[k++] = myArray[n++];
    for(m = m1, n = 0; m <= n2; m++, n++)
        myArray[m] = tmpStorage[n];
}

void main()
{
  printf("Enter the 10 integers for merge sort separated by white spaces: \n");
  for (int i=0; i < count; i++)
    scanf("%d", &myArray[i]);
  fflush(stdin);
  mergeSort(0, count-1);
  printf("Sorted List: ");
  for(int i = 0; i < count; i++)
    printf("%d ",myArray[i]);
}

Result


Related Tutorials