컴퓨터 프로그래밍
알고리즘 - 선택 정렬(Selection Sort) 소스 코드
THINK_PRO
2013. 9. 26. 00:38
<문제>
Input (Standard input)
In the first line, the number of input keys N, and the integer M are given(1≤N,M≤30,000).
In the next N lines, a key is given in each line.
Output (Standard output)
Print the key after the M steps of the selection sort. (Sort in increasing order.)
#include <stdio.h>
#include <stdlib.h>
// parameter:
// 'arr' is the array to sort.
// 'len' is the length of the array.
// 'count' means the steps of the selection sort.
void SelectionSort( int arr[], int len, int count )
{
int i, j, minIdx, tmp;
for( i=0; i<count; i++ )
{
minIdx = i;
for( j=i+1; j<len; j++ )
{
if( arr[j] < arr[minIdx] )
minIdx = j;
}
if( i != minIdx)
{
tmp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = tmp;
}
}
}
int main( void )
{
int i; // for repetition
int len, count;
int * arr;
/* Input */
scanf("%d %d", &len, &count); // 길이(N)와 스텝(M) 입력.
arr = ( int* )malloc( sizeof(int) * len ); // 그 길이에 맞춘 배열 생성
for( i=0; i < len; i++ )
{
scanf("%d", &arr[i]); // 배열 원소들의 값들 입력받기
}
/* Output */
SelectionSort( arr, len, count ); // 선택 정렬.
for( i=0; i < len; i++ )
{
printf("%d\n", arr[i]); // 각 값들 모두 출력하기
}
free(arr);
return 0;
}