PROGRAM FOR SORTING ARRAY USING MERGE SORT.
#include <iostream>
#include <conio.h>
using namespace std;
class Array
{
private:
int *Arr, Size, Right;
public:
Array(int Siz)
{
Arr = new int[Siz];
for (int I = 0; I <Siz; I++)
{
Arr[I] = 0;
}
Right = 0;
Size = Siz;
}
void Input()
{
int No;
cout << "Enter Size Of Array: ";
cin >> No;
Right = No;
cout << "\nEnter Elements Of Array: " << endl;
for (int I = 0; I <Right; I++)
{
cin >> Arr[I];
}
}
void Merge_Sort()
{
Sorting(Arr, 0, Right -1);
}
void Sorting(int Temp[], int Beg, int End)
{
int Mid;
Mid = (Beg + End) /2;
if(Beg >= End)
return;
Sorting(Temp, Beg, Mid);
Sorting(Temp, Mid +1, End);
Merge_Array(Temp, Beg, Mid, End);
}
void Merge_Array(int Temp[], int Beg, int Mid, int End)
{
int Size1 = Mid - Beg +1;
int Size2 = End - Mid;
int Array1[Size1], Array2[Size2];
for(int I = 0; I <Size1; I++)
Array1[I] = Temp[Beg +I];
for(int J = 0; J <Size2; J++)
Array2[J] = Temp[Mid +1 +J];
int I, J, K;
I = J = 0;
K = Beg;
while(I < Size1 && J < Size2)
{
if(Array1[I] < Array2[J])
Temp[K] = Array1[I++];
else
Temp[K] = Array2[J++];
K++;
}
while(I <Size1)
Temp[K++] = Array1[I++];
while(J <Size2)
Temp[K++] = Array2[J++];
}
void Print()
{
cout << "\nElements Of Array is: " << endl;
for (int I = 0; I <Right; I++)
cout << Arr[I] << endl;
}
~Array()
{
cout << "\n\n\n\n************PROGRAM ENDED***************";
}
};
int main()
{
Array Obj(20);
Obj.Input();
Obj.Merge_Sort();
Obj.Print();
getch();
return 0;
}
0 comments:
Post a Comment