Merge Sort Algorithm

Merge sort is a divide and conquer comparison-based sorting algorithm.

Algorithm:

  1. If the list is of length 0 or 1, then it is already sorted. Otherwise:
  2. Divide the unsorted list into two sublists of about half the size.
  3. Sort each sublist recursively by re-applying the merge sort.
  4. Merge the two sublists back into one sorted list.
#include<stdio.h>

void merge(float arr[], int lo, int mid, int hi){	
	int i;
	int j;
	int k;
	float temp[hi];

	// copy arr to temp
for (i = lo; i <= hi; i++) temp[i] = arr[i]; i = lo; j = mid + 1; k = lo; while (i <= mid && j <= hi) if (temp[i] <= temp[j]) arr[k++] = temp[i++]; else arr[k++] = temp[j++]; // copy back remaining elements of first half (if any)
while (i <= mid) arr[k++] = temp[i++]; } void mergesort(float arr[], int lo, int hi){ int mid; if (lo < hi){ mid = (lo + hi) / 2; mergesort(arr, lo, mid); mergesort(arr, mid + 1, hi); merge(arr, lo, mid, hi); } } int main(){ int i; int n; float arr[30]; //number of items to be sorted
printf("How many items to be sorted:"); scanf("%i", &n); //items to be sorted
for(i = 0; i < n; i ++){ printf("Item %i: ", i+1); scanf("%f", &arr[i]); } mergesort(arr, 0, n - 1); for (i = 0; i < n; i++) printf("%.2f ", arr[i]); return 0; }

 

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.