반응형
버블정렬 코드 입니다.
- i 와 i + 1을 비교하여 i 가 더 클 경우에 스왑하고 더 이상 필요 없을 때 까지 반복 합니다.
- 버블보다 삽입정렬의 복잡도가 더 좋습니다.
성능
- 최악의 경우 : O(n^2)
- 최선의 경우 : O(n)
- 평균 : O(n^2)
- 최악의 경우 공간 복잡도 : O(1)
static void BubbleSort(int[] a)
{
for (int pass=a.Length-1; pass >= 0; pass--)
{
for (int i=0; i<pass; i++)
{
if (a[i] > a[i+1])
{
// swap
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
}
테스트
using System;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Bubble sort");
int[] numbers = { 2, 10, 3, 7, 1, 4, 3, 5, 8 };
Print(numbers);
BubbleSort(numbers);
Print(numbers);
}
static void Print(int[] a)
{
string temp = "";
for (int i = 0 ;i < a.Length; i++)
temp += a[i].ToString();
Console.WriteLine(temp);
}
static void BubbleSort(int[] a)
{
for (int pass=a.Length-1; pass >= 0; pass--)
{
for (int i=0; i<pass; i++)
{
if (a[i] > a[i+1])
{
// swap
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
}
}
}
결과
반응형
'Programing > C#' 카테고리의 다른 글
복리 계산기 (0) | 2021.02.16 |
---|---|
Selection Sort (선택 정렬) (0) | 2021.02.16 |
do while의 활용 법 featuring ReadAsStreamAsync(비동기 스트림) (0) | 2020.02.18 |
double vs decimal (0) | 2020.02.11 |
c# reflection 을 이용해서 assembly의 type과 method의 갯수 파악하기 (0) | 2020.02.11 |