https://www.toptal.com/developers/sorting-algorithms

 

Sorting Algorithms Animations

Animation, code, analysis, and discussion of 8 sorting algorithms on 4 initial conditions.

www.toptal.com

public class Ex04_selection {

	public static void main(String[] args) {
		// Selection Sort
		int []num = new int[] {25,15,10,5,12,9,17,23,13,19};
		int t;
		
		System.out.print("Source data : ");
		for(int n: num) {
			System.out.printf("%5d", n);
		}
		System.out.println();
		
		// 정렬
		for(int i=0; i<num.length-1; i++) { // i=0; i<9; i++ 9회전
			for(int j=i+1; j<num.length; j++) {
				if(num[i] > num[j]) { // 부등호에 따라 오름차순, 내림차순
					t = num[i];
					num[i] = num[j];
					num[j] = t;
				}
			}
		}
		
		System.out.print("Sort data : ");
		for(int n: num) {
			System.out.printf("%5d", n);
		}
		System.out.println();
	}

}

Selection 정렬 : 가장 앞에 가장 작은 값을 놓는다.


50 25 60 35 40
1회전 : (1번째:2번째)(1번째:3번째)(1번째:4번째)(1번째:5번째)
25 : 50 / 25 : 60 /  25: 35 / 25 : 40
결과 : 25 50 60 35 40 
총 비교 횟수 n(n-1)/2
가장 쉬운 정렬 방식

 

+ Recent posts