Tuesday, 22 January 2013

Merge Sort

Easy Method :


#include < stdio.h > 
#include < conio.h >
  void simple_merge(int a[], int low, int mid, int high)
  {
    int i, j, k, c[20];
    k = low;
    i = low;
    j = mid + 1;
    while((I <= mid) && (j <= high))
    {
      if(a[i] < a[j])
        c[k++] = a[i++];
      else
        c[k++] = a[j++];
    }
    while(i <= mid)
      c[k++] = a[i++];
    while(j <= high)
      c[k++] = a[j++];
    for(i = low; i <= k - 1; i++)
      a[i] = c[i];
  }
void mergesort(int a[], int low, int high)
{
  int mid;
  if(low < high)
  {
    mid = (low + high) / 2;
    mergesort(a, low, mid);
    mergesort(a, mid + 1, high);
    simple_merge(a, low, mid, high);
  }
}
int main()
{
  int i, n, a[20];
  printf("enter the value for n \n");
  scanf("%d", & n);
  printf("enter the values for the array \n");
  for(i = 0; i < n; i++)
    scanf("%d", & a[i]);
  mergesort(a, 0, n - 1);
  printf("\n The sorted elements are \n");
  for(i = 0; i < n; i++)
    printf("%d\t", a[i]);
  getch();
}

No comments:
Write comments

Featured post

List of Universities in Karnataka offering M.Sc Computer Science

The post-graduate programme in Computer Science (M.Sc Computer Science) contains two academic years duration and having a four semesters....

Popular Posts

Copyright @ 2011-2016