Anonymous Anonymous - 1 month ago
110 0

No description

C

mergesort

Embed
#include <stdio.h>
#include <stdlib.h>

//Written by DevDAG...

void Merge(int* arr,int* L, int leftsize, int* R, int rightsize){
	
	int i = 0, j = 0, k = 0;
	
	
	while(i < leftsize && j < rightsize){
		if(L[i] < R[j]) arr[k++] = L[i++];
		else arr[k++] = R[j++];
	}
	while(i < leftsize) arr[k++] = L[i++]; 
	while(j < rightsize) arr[k++] = R[j++];
	
	
}

void mergeSort(int* arr, int size){
	if(size < 2) return;
	
	int mid = size/2;
	int *L,*R,i;	
	
	L = (int*)malloc(mid*sizeof(int));
	R = (int*)malloc((size-mid)*sizeof(int));
	
	for(i = 0; i < mid; i++) L[i] = arr[i];
	for(i = mid; i < size; i++) R[i-mid] = arr[i];
	
	mergeSort(L,mid);
	mergeSort(R,size-mid);
	Merge(arr, L, mid, R, size-mid);		
	free(L);
	free(R);
}


int main(){
	int arraysize,i;
	int* array;
	printf("Enter array size: ");
	scanf("%d",&arraysize);
	
	array = (int*)malloc(arraysize*sizeof(int)); //allocationg the array.
	
	printf("Enter the elements: ");
	for(i = 0; i < arraysize; i++){
		scanf("%d",&array[i]);
	}
	
	mergeSort(array,arraysize);
	
	for(i = 0; i < arraysize; i++) printf("%d ", array[i]);
	
	free(array);
	
	return 0;
}
Comments