티스토리 뷰

공부 이야기

[C] 선택 정렬

판다(panda) 2009. 9. 16. 00:02

전에 한번 썼는데.. 색 넣기가 귀찮아서;.. 그냥 그대로 넣습니다..

Microsoft Visual Studio 2005 버전으로 작성되었습니다..
미리 컴파일 된 헤더를 사용했습니다..
선택 정렬..



#include "stdafx.h"
#include <stdlib.h>

// A[] : 데이터 배열
// n : 데이터 갯수
// A[0..n] 배열을 정렬한다.

// 비쥬얼 요소 추가

void Display(int A[], int n);

void selectionSort(int A[], int n)
{

 for(int last=n-1; last>=1; last--)
 {

  // A[0..last] 중 가장 큰 수 A[k]를 찾는다.
  int k=0;
  for(int i=1; i<=last; i++)

   if(A[k]<A[i])

    k=i;

  // A[k] <=> A[last];
  int t = A[k];
  A[k] = A[last];
  A[last] = t;

  Display(A, n);

 }

}

void Display(int A[], int n)
{

 system("cls");
 for(int i=0; i<n; i++)
 {

  printf("%2d ", A[i]);
  for(int j=0; j<A[i]; j++)

   putchar('#');

  printf("\n");

 }
 _sleep(100);

}


int _tmain(int argc, _TCHAR* argv[])
{

 int A[] = {8, 31, 48, 73, 3, 65, 20, 29, 11, 15};

 selectionSort(A,10);

 Display(A, 10);

 return 0;

}

실행결과 : 정렬이 되는 과정을 보여준다.



#include "stdafx.h"
#include <stdlib.h>

void Display(int A[], int n);

void selectionSort(int A[], int n)
{

 if(n==1)

  return;

 for(int last=n-1; last>=1; last--)
 {

  // A[0..n-1] 중 가장 큰 수 A[k]를 찾는다.
  int k=0;
  for(int i=1; i<n; i++)

   if(A[k]<A[i])

    k=i;

  // A[k] <=> A[last];
  int t = A[k];
  A[k] = A[n-1];
  A[n-1] = t;
  
  Display(A, n);
 }

 // 문제의 크기를 하나 줄여서 실행
 selectionSort(A, n-1);

}

void Display(int A[], int n)
{

 system("cls");
 for(int i=0; i<n; i++)
 {

  printf("%2d ", A[i]);
  for(int j=0; j<A[i]; j++)

   putchar('#');

  printf("\n");

 }
 _sleep(100);

}


int _tmain(int argc, _TCHAR* argv[])
{

 int A[] = {8, 31, 48, 73, 3, 65, 20, 29, 11, 15};

 selectionSort(A,10);

 Display(A, 10);

 return 0;

}

실행결과 : 비교하여 정렬 후 화면에서 삭제.. 그리고 결과 출력..