반응형
배열로 선택정렬 구현
public static void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static int[] selectSort(int[] array) {
int min;
for (int i = 0; i < array.length; i++) {
min = i;
for (int j = i+1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
swap(array, min, i);
}
return array;
}
버블정렬
public static void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static int[] bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
// 앞에서부터 값을 비교하면서 큰 값을 뒤로 보내는 것
for (int j = 1; j < array.length - i; j++) {
if (array[j-1] > array[j]) {
swap(array, j-1, j);
}
}
return array;
}
}
삽입정렬
public static int[] insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {
//i-1까지는 정렬되어 있다.
int item = array[i];
int loc = i-1;
// 왼쪽으로 가면서 item이 작으면 바꾼다
while(loc >= 0 && item < array[loc]) {
array[loc + 1] = array[loc];
loc--;
}
// 더 이상 작지 않을 때 그 값의 오른쪽에 삽입
array[loc + 1] = item;
}
return array;
}
'Algorithm' 카테고리의 다른 글
[Java] 백준 그리디 알고리즘 (0) | 2021.04.21 |
---|---|
[Java] (0) | 2021.04.19 |
[Python] 프로그래머스 완전탐색 모의고사 (0) | 2021.04.07 |
[Python] 정렬 (0) | 2021.04.04 |
[Python] DFS, BFS (0) | 2021.04.04 |