#include <iostream>
using namespace std;
class sort1{
public: void mergelist(int Data[], int first, int mid, int last);
void mergeSort(int A[], int ledt, int right);
};
// trien khai cac ham trong class
void sort1::mergelist(int Data[], int first, int mid, int last){
int tmp[100];
int first1 = first;
int last1 = mid;
int first2 = mid+1;
int last2 = last;
int index = first1;
while((first1<=last1)&&(first2<=last2)){
if(Data[first1]<Data[first2]){
tmp[index] = Data[first1];
first1++;
}
else{
tmp[index] = Data[first2];
first2++;
}
++index;
}
while(first1<=last1){
tmp[index] = Data[first1]; // sao not cac phan tu con lai vao mang nho
++index;
++first1;
}
while(first2<=last2){
tmp[index] = Data[first2]; // sao not cac phan tu con lai vao mang nho
++index;
++first2;
}
for(index = first;index<=last; index++){
Data[index] = tmp[index];
}
}
// goi ham mergeSort
void sort1::mergeSort(int A[], int left, int right){
if(left>=right) return;
else{
int mid=(left+right)/2;
mergeSort(A, left, mid);
mergeSort(A, mid+1, right);
mergelist(A, left, mid, right);
}
}
int main()
{
sort1 srt;
int A[100];
int n;
cout<<"Nhap so phan tu cua mang: "<<endl;
cin>>n;
for(int i=1; i<=n; i++){
cout<<"Phan tu thu "<<i<<" la: ";
cin>>A[i];
}
srt.mergeSort(A,1,n);
for(int i=1; i<=n; i++){
cout<<" "<<A[i];
}
return 0;
}
0 nhận xét:
Đăng nhận xét