algorithm 삽입정렬

Algorithm 2015. 7. 8. 20:19

삽입정렬 - 오름차순

public class Main {
	public static void main(String[] args) {
		int[] a = {31, 41, 6, 26, 41, 58, 99, 85, 59, 14};
		int key = 0;
		int i = 0, j = 0;
		
		//정렬 전 배열 출력
		for(int out : a) {
			System.out.print(out + " ");
		}
		System.out.println();
		
		//insertion sort 오름차순
		for(i = 1; i < a.length; i++) {
			key = a[i];
			j = i - 1;
			while(j>=0 && a[j]>key) {
				a[j+1] = a[j];
				j--;
			}
			a[j+1] = key;
		}
		
		//정렬 후 배열 출력
		for(int out : a) {
			System.out.print(out + " ");
		}
		System.out.println();
	}
}


삽입정렬 - 내림차순

public class Main {
	public static void main(String[] args) {
		int[] a = {31, 41, 6, 26, 41, 58, 99, 85, 59, 14};
		int key = 0;
		int i = 0, j = 0;
		
		//정렬 전 배열 출력
		for(int out : a) {
			System.out.print(out + " ");
		}
		System.out.println();
		
		//insertion sort 내림차순
		for(i = a.length-2; i >= 0; i--) {
			key = a[i];
			j = i + 1;
			while(j<a.length && a[j]>key) {
				a[j-1] = a[j];
				j++;
			}
			a[j-1] = key;
		}

		//정렬 후 배열 출력
		for(int out : a) {
			System.out.print(out + " ");
		}
		System.out.println();
	}
}

'Algorithm' 카테고리의 다른 글

algorithm 병합정렬  (0) 2015.07.09
algorithm 버블 정렬  (0) 2015.07.09
algorithm 문자사각형1  (0) 2015.07.01
: