Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void merge(int values[], int iStart, int iEnd, int jStart, int jEnd){
- int temp[100], i = iStart, j = jStart, count = 0;
- while(i<=iEnd && j <= jEnd) //index at which number is least will be copoed to temp[]
- if (values[i] <= values[j]) temp[count++] = values[i++];
- else temp[count++] = values[j++];
- while(i <= iEnd) temp[count++] = values[i++];//If j reaches jEnd, elements from i are copied
- while(j <= jEnd) temp[count++] = values[j++];//If i reaches iEnd, elements from j are copied
- count--;
- while(count >= 0) {
- values[iStart + count] = temp[count];
- count--;
- }
- }
- void mergeSort(int values[], int start, int end){
- if (start < end){
- int mid = (start+end)/2;//recursvly dividing in half
- mergeSort(values, start, mid);
- mergeSort(values, mid+1, end);
- merge(values, start, mid, mid+1, end);//two sorted arrays will be merged
- }
- }
- int main(){
- int *values, n;
- printf("Enter the number of elements: ");
- scanf("%d", &n);
- values = (int*) malloc(sizeof(int) * n);
- for(int i = 0; i < n; i++) scanf("%d", &values[i]);
- mergeSort(values, 0, n-1);
- for(int i = 0; i < n; i++) printf("%d ", values[i]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement