알고리즘 공부
C# 버블 정렬
프로핌
2023. 7. 21. 16:51
버블 정렬은 오른쪽 부터 왼쪽 방향으로 인접한 두개 숫자를 비교해서 왼쪽숫자가 더 크면 교환을하고 아니면 가만히 있고
그렇게 오름차순으로 정렬을 하는 배열 알고리즘이다.
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[] 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++)
{
for (int j = a.Length - 1; j != i; j--)
{
if (a[j] < a[j - 1])
{
int temp;
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
foreach(int b in a)
{
Console.Write($"{b} ");
}
}
}
}
이렇게 짜면 내가 배열의 크기와 그 배열을 입력할때 오른쪽부터 왼쪽을 비교를해서 오름차순으로 정렬을 해준다.