C# 선택 정렬
2023. 7. 21. 17:20ㆍ알고리즘 공부
선택 정렬은 수열중에서 최솟값을 찾아서 왼쪽 숫자와 비교를하고 더 작으면 교체하는 작업을 계속해서 오름차순으로
정렬하는 알고리즘이다.
수열중에서 최솟값을 찾을 때는 선형 탐색 사용
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 선택정렬
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int index = 0;
int[] a = new int[n];
string[] arr = Console.ReadLine().Split();
for (int i = 0; i < a.Length; i++)
{
a[i] = int.Parse(arr[i]);
}
for (int i = 0; i < a.Length; i++)
{
int min = int.MaxValue;
for (int j = i + 1; j < a.Length; j++)
{
if (a[j] < min)
{
min = a[j];
index = j;
}
}
if (a[i] > a[index])
{
int temp;
temp = a[i];
a[i] = a[index];
a[index] = temp;
}
}
foreach (int b in a)
{
Console.Write($"{b} ");
}
}
}
}
이렇게 코드를 짜면 수열중에 최솟값을 찾은다음에 왼쪽 숫자와 비교를하고 더 작으면 교체를 하면서 오름차순으로 정렬하는 선택 정렬 알고리즘이 완성된다.
'알고리즘 공부' 카테고리의 다른 글
C# BFS 너비우선탐색 (0) | 2023.08.15 |
---|---|
C# 힙 정렬 (0) | 2023.07.25 |
C# 삽입 정렬 (0) | 2023.07.22 |
C# 버블 정렬 (0) | 2023.07.21 |
내가 이해한 대로 글을 쓰는 데이터 구조 (0) | 2023.07.21 |