2009년 09월 18일
[C#] 간단한 버블 소트 작성하기
정수 데이터를 사용한 간단한 Bubble sorting 프로그램 예제를 작성해 본다.
버블 소트는 n 개의 데이터에 대하여 이중 for loop를 한 번 실행해 주면 된다.
최고 효율의 소팅 알고리즘은 아니지만, 코드가 간단하기 때문에 많이 사용한다.
<Sort.cs> - C# express 2008의 콘솔응용프로그램
============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // 사용자 추가
using System.Collections; // 사용자 추가
namespace Sort
{
class Program
{
static void Main(string[] args)
{
// 파일에서 데이터 읽기
StreamReader fi = new StreamReader("d:\\input.txt");
ArrayList nums_array = new ArrayList();
// 입력 데이터의 갯수를 모르기 때문에, 읽어서 ArrayList에 저장한다.
string line1 = fi.ReadLine();
while (line1!=null)
{
nums_array.Add(Convert.ToInt32(line1));
line1 = fi.ReadLine();
}
// ArrayList를 정수 array로 변환
int[] nums = (int[])nums_array.ToArray(typeof(int));
int temp;
// 버블 소트
for (int i=0;i<nums.Length-1; i++)
for (int j=i+1; j<nums.Length; j++)
if (nums[i]>nums[j]) // 오름차순 정렬
{
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
fi.Close();
// 콘솔(도스창)으로 출력
for (int i=0; i<nums.Length; i++)
Console.WriteLine("{0}", nums[i]);
Console.ReadKey();
}
}
}
===============================================================
<input.txt> 입력 데이터
==========================
58
35
61
79
39
11
7
97
43
83
55
14
48
==========================
<출력 화면>

이 글과 관련있는 글을 자동검색한 결과입니다 [?]
- Thread pool 예제 by 동그리
- 소설같은 p666 ICollection 으로하는 동기화 ..잘은 ... by 동그리
- 소설같은 Thread 하나의 객체를 Thread 돌릴때 Lock로~~ by 동그리
- 중첩 마스터 페이지의 FindControl로 컨트롤 찾기 by ultteky
- Threaed 상태 제어 by 동그리
# by | 2009/09/18 19:05 | 프로그래밍 | 트랙백 | 덧글(0)





☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]