C/C++/MFC
C기초 합병정렬(MERGE SORT)
2008.03.14 23:19
합병정렬(MERGE SORT)
// win4.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include<iostream> #include<iomanip> using namespace std; class CWATmergesort { private: int *x,*y,*z; int items1,items2; public: CWATmergesort(int,int); ~CWATmergesort(); void input1(int []); void input2(int []); void msort(int [], int); void display(); void sort(); }; CWATmergesort::CWATmergesort(int p,int q) { items1=p; items2=q; x=new int[items1]; y=new int[items2]; z=new int[items1+items2]; } CWATmergesort::~CWATmergesort() { delete [] x; delete [] y; delete [] z; } void CWATmergesort::input1(int a[]) { for(int i=0;i<items1;i++) x[i]=a[i]; msort(x,items1); cout<<"\n Sorted first array :"; for(i=0;i<items1;i++) cout<<setw(5)<<x[i]; } void CWATmergesort::input2(int b[]) { for(int i=0;i<items2;i++) y[i]=b[i]; msort(y,items2); cout<<"\n Sorted second array : "; for(i=0;i<items2;i++) cout<<setw(5)<<y[i]; } void CWATmergesort::msort(int m[],int n) { int swap=1; for(int i=0;i<n && swap==1;i++) { swap=0; for(int j=0;j<n-(i+1);j++) { if(m[j]>m[j+1]) { int temp; temp=m[j]; m[j]=m[j+1]; m[j+1]=temp; swap=1; } } } } void CWATmergesort::display() { cout<<"\n Sorted elements are :"; for(int i=0;i<items1+items2;i++) cout<<setw(5)<<z[i]; } void CWATmergesort::sort() { int i,j,k; i=j=k=0; while((i<items1) && (j<items2)) { if(x[i]<y[j]) { z[k]=x[i]; i++; k++; } else { if(x[i]>y[j]) { z[k]=y[j]; j++; k++; } else { z[k]=x[i]; i++; j++; k++; } } } while(i<items1) { z[k]=x[i]; i++; k++; } while(j<items2) { z[k]=y[j]; j++; k++; } } int main() { int elements1[100]={1,2,13,4,7}; int n1=5; int elements2[100]={111,222,33,44,77}; int n2=5; CWATmergesort obj(n1,n2); obj.input1(elements1); obj.input2(elements2); obj.sort(); obj.display(); return 0; }
<결과> Sorted first array : 1 2 4 7 13 Sorted second array : 33 44 77 111 222 Sorted elements are : 1 2 4 7 13 33 44 77 111 222 Press any key to continue
관련 문서가 검색되었습니다.
- [2013/06/25] string array to string (스트링 문자열 합치기) (23713)
- [2013/06/20] 5명의 키를 읽어 들여 가장 큰 키와 작은 키를 구하는 프로그램을 작성하시오 (12064) *1
- [2011/03/29] C# DataGridView 간단하게 필터 기능 사용하기 (27985)
- [2010/09/17] ListView Sort 정렬하기 (22346) *1
- [2008/03/14] 쉘 정렬(SHELL SORT) ()
- [2008/03/14] 퀵 정렬(QUICK SORT) ()
- [2008/03/14] 힙 정렬(HEAP SORT) ()
- [2008/03/14] 버블 정렬(BUBBLE SORT) ()