반응형
Selection Sort
Selection sort is one of the simplest sorting algorithms.
It repeatedly selects the smallest value from the given list and moves it to the front, thereby sorting the list
Process Explanation
- Find the smallest value in the given list.
- Swap the smallest value with the first element of the list.
- Find the smallest value in the remaining unsorted part of the list (excluding the sorted region).
- Swap the smallest value with the first element of the unsorted part.
- Repeat steps 3 and 4 until the entire list is sorted.
Example code
package Algorithm;
import java.util.Arrays;
public class SelectionSort {
/**
* Swapping the values at positions i and j (Exchanging the values of array[j], which is the smallest value, and array[i])
*/
public static void swapElements(int[] array , int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
* Find the position of the minimum value starting from "start" (including start)
* go up to the last position of the array.
*/
public static int indexLowest(int[] array, int start) {
int lowIndex = start;
for (int i = start; i < array.length; i++) {
if (array[i] < array[lowIndex]) {
lowIndex = i;
}
}
return lowIndex;
}
/**
* Sort the elements using the selection sort algorithm.
*/
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = indexLowest(array, i);
swapElements(array, i, j);
}
}
public static void main(String[] args) {
int[] array = {10, 5, 7, 9, 1, 8, 2, 100, 42, 26, 32, 8, 11};
selectionSort(array);
System.out.println(Arrays.toString(array));
}
/**
* Result [1, 2, 5, 7, 8, 8, 9, 10, 11, 26, 32, 42, 100]
*/
}
Time complexity and efficiency
Selection sort is not a stable sorting algorithm, and its time complexity is O(n^2).
This means that the number of operations increases quadratically as the size of the list increases.
Therefore, when sorting a large amount of data, it is recommended to use other more efficient algorithms.
반응형
'Algorithm' 카테고리의 다른 글
백준 1157 번 (단어공부) - 자바(JAVA) (0) | 2023.06.15 |
---|---|
백준 9095 문제 (순열을 이용한 풀이 및 dp 풀이) - 자바(JAVA) (0) | 2023.06.14 |
선택 정렬(Selection Sort) - 자바(JAVA) (0) | 2023.06.13 |
우선순위 큐(Priority Queue) - 자바(JAVA) (0) | 2023.06.13 |
DP(Dynamic Programming) - 자바(JAVA) (0) | 2023.06.13 |