본문 바로가기

C/C++/예제

[C++ 예제] 삽입, 선택 정렬

반응형

C++ 예제 소스.

 

삽입, 선택 정렬.

 

 

소스.

#include
#define MAX 5
void insert_sort (int a[], int n);
void select_sort (int a[], int n);

int main()
{
 int i, n, m;
 int a[MAX];
 cout << "Number of data (MAX = 5) : ";
 cin >> n;

 for(i = 0; i < n; i++){
  cout << (i+1) << "'s number : ";
  cin >> a[i];
 }
 
 cout << endl << " Input data : ";
 for(i = 0; i < n; i++){
  cout << " " << a[i];
 }

 cout << endl << "삽입정렬 = 1번." << endl << "선택정렬 = 2번."<< endl;
 cin >> m;
 switch(m){
 case 1:
  insert_sort (a, n);
  break;
 case 2:
  select_sort(a, n);
  break;
 default:
  cout << "잘못 입력하셨습니다." << endl;
  return 1;
 }
 
 cout << endl << " Sorted data : ";
 
 for(i = 0; i < n; i++){
  cout << " " << a[i];
 }
 cout << endl;

 return 0;
} 

void select_sort(int a[], int n) 
{
    int i, j, min, temp;
    for (i=0; i < n-1; i++){
        min = i;
        for (j=i+1; j < n; j++){
            if (a[j] < a[min])
                   min = j;
         }
        temp = a[min];
        a[min] = a[i];
        a[i] = temp;
    }
}

void insert_sort (int a[], int n)
{
 int i, j, k;
 for(i = 1; i < n; i++){
  k = a[i];
  for(j = i-1; ( j > 0 && k < a[j] ); j--){
   a[j+1] = a[j];
  }
  a[j+1] = k;
 }
}

 

 

반응형