기본 정렬 알고리즘(selection, bubble, insertion sort)

라리·2021년 10월 12일
0

알고리즘

목록 보기
5/6

1. Selection sort(선택정렬)

각 루프마다
1) 최대 원소를 찾는다
2) 최대 원소와 맨 오른쪽 원소를 교환한다.
3) 맨 오른쪽 원소를 제외한다.
하나의 원소만 남을 때까지 위의 루프를 반복한다.

👩‍💻구현

package Algorithm;

public class selection_sort {
	private static int[] input = {5, 6, 2, 8, 7, 23, 4, 1};
	
	public static void main(String[] args) {
		selectionSort(input, input.length);
	
		for(int i : input) {
			System.out.print(i + " ");
		}	

	}
	
	public static void selectionSort(int[] input, int inputLength) {
		int max;
		int tmp;
		
		for(int i=0; i<inputLength; i++) {
			max = i;
			for(int j=i+1; j<inputLength; j++) {
				if(input[j] > input[i]) {
					max = j;
				}
			}
			
			tmp = input[i];
			input[i] = input[max];
			input[max] = tmp;
		}
	}

}

2. Bubble Sort(버블정렬)

👩‍💻구현

package Algorithm;

public class bubble_sort {
	private static int[] input = {5, 6, 2, 8, 7, 23, 4, 1};
	
	public static void main(String[] args) {
		bubbleSort(input, input.length);
		
		for(int i : input) {
			System.out.print(i + " ");
		}
	}
	
	public static void bubbleSort(int[] input, int length) {
		int tmp;
		
		for(int i=length-1; i>0; i--) {
			for(int j=0; j<i; j++) {
				if(input[j] > input[j+1]) {
					tmp = input[j];
					input[j] = input[j+1];
					input[j+1] = tmp;
					
				} 
			}
		}
	}

}

3. Insertion Sort(삽입정렬)

👩‍💻구현

package Algorithm;

public class insertion_sort {
	private static int[] input = {5, 6, 2, 8, 7, 23, 4, 1};

	public static void main(String[] args) {
		insertionSort(input, input.length);
		
		for(int i : input) {
			System.out.print(i + " ");
		}

	}
	
	public static void insertionSort(int[] input, int length) {
		int tmp;
		
		for(int i=1; i<length; i++) {
			for(int j=i; j>0; j--) {
				if(input[j] < input[j-1]) {
					tmp = input[j];
					input[j] = input[j-1];
					input[j-1] = tmp;
				}
			}
		}
	}

}

출처: https://ict-nroo.tistory.com/52?category=698685 [개발자의 기록습관]

0개의 댓글