Merge Sort
The following implementation is in object oriented using the MergeSort class and ms object. Actual logic of Merge sort is in the function of Merge().The following C++ code will explains the implementation of Merge Sort and sort the user input numbers in descending order.
In MergeSort.h
#include "iostream" using namespace std; class MergeSort { public: int first[3], second[3], third[6]; public: void Sort(int *arr) { for (int i = 0; i <= 2; ++i) { for (int j = i+1; j <= 2; ++j) { if (arr[i] > arr[j]) //Descending (small to big) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } void Merge() { int i = 0, j = 0; for (int z = 0; z <= 5;) { if ((first[i] <= second[j]) && (i != 3)) { third[z] = first[i]; ++i; } else if (j != 3) { third[z] = second[j]; ++j; } ++z; if ((i == 3) || (j == 3)) { if (i == 3) third[z] = second[j]; else third[z] = first[i]; ++z; } } } };In main.cpp
#include "MergeSort.h" int main() { MergeSort ms; for (int i = 0; i <= 2; ++i) { cout << "Enter values in 1st array : " << i+1 << " of 3: "; cin >> ms.first[i]; } ms.Sort(ms.first); cout << endl; for (int i = 0; i <= 2; ++i) { cout << "Enter values in 2nd array : " << i+1 << " of 3: "; cin >> ms.second[i]; } ms.Sort(ms.second); ms.Merge(); cout << "\n\nAfter Merge Sort input numbers are\n"; for (int i = 0; i <= 5; ++i) { cout << ms.third[i] << "\t"; } return 0; }
No comments:
Post a Comment
Your valuable comments are appreciated...!