Advertisement
Shailrshah

Merge Sort

Sep 12th, 2013
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void merge(int values[], int iStart, int iEnd, int jStart, int jEnd){
  4.     int temp[100], i = iStart, j = jStart, count = 0;
  5.     while(i<=iEnd && j <= jEnd) //index at which number is least will be copoed to temp[]
  6.         if (values[i] <= values[j]) temp[count++] = values[i++];
  7.         else temp[count++] = values[j++];
  8.     while(i <= iEnd) temp[count++] = values[i++];//If j reaches jEnd, elements from i are copied
  9.     while(j <= jEnd) temp[count++] = values[j++];//If i reaches iEnd, elements from j are copied
  10.     count--;
  11.     while(count >= 0) {
  12.         values[iStart + count] = temp[count];
  13.         count--;
  14.     }
  15. }
  16. void mergeSort(int values[], int start, int end){
  17.     if (start < end){
  18.         int mid = (start+end)/2;//recursvly dividing in half
  19.         mergeSort(values, start, mid);
  20.         mergeSort(values, mid+1, end);
  21.         merge(values, start, mid, mid+1, end);//two sorted arrays  will be merged
  22.     }
  23. }
  24. int main(){
  25.     int *values, n;
  26.     printf("Enter the number of elements: ");
  27.     scanf("%d", &n);
  28.     values = (int*) malloc(sizeof(int) * n);
  29.     for(int i = 0; i < n; i++) scanf("%d", &values[i]);
  30.     mergeSort(values, 0, n-1);
  31.     for(int i = 0; i < n; i++) printf("%d ", values[i]);
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement