This a Cpp program which sorts all the elements using Merge Sort Technique. |
See the animation below,
"Merge-sort-example-300px" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.
PROGRAM :
#include <iostream> using namespace std; void mergeSort(int [], int, int, int); void partition(int [],int, int); int main() { int list[50]; int i, n; cout << "How many numbers ? \t"; cin >> n; cout << "\n\n"; for(i = 0; i < n; i++) { cout << "Enter number " << i+1 << ":\t"; cin >> list[i]; } partition(list, 0, n - 1); cout << "\n\nAfter merge sort:\n"; for(i = 0; i < n; i++) { cout << list[i] << "\t"; } cout << "\n\n"; return 0; } void partition(int list[],int low,int high) { int mid; if(low < high) { mid = (low + high) / 2; partition(list, low, mid); partition(list, mid + 1, high); mergeSort(list, low, mid, high); } } void mergeSort(int list[],int low,int mid,int high) { int i, midd, k, loww, temp[50]; loww = low; i = low; midd = mid + 1; while ((loww <= mid) && (midd <= high)) { if (list[loww] <= list[midd]) { temp[i] = list[loww]; loww++; } else { temp[i] = list[midd]; midd++; } i++; } if (loww > mid) { for (k = midd; k <= high; k++) { temp[i] = list[k]; i++; } } else { for (k = loww; k <= mid; k++) { temp[i] = list[k]; i++; } } for (k = low; k <= high; k++) { list[k] = temp[k]; } }
OUTPUT :
Cpp - Merge Sort |