-
버블 정렬(Bubble Sort), 선택 정렬(Selection Sort)자료구조 2021. 3. 26. 13:50
버블 정렬(Bubble Sort)
- 인접한 두개의 원소를 비교하여 자리를 교환하는 방식을 첫 번째 원소부터 마지막 원소까지 반복한다.
- 한 단계가 끝나면 가장 큰 원소가 마지막 자리로 정렬된다.
- O(N²)
출처: Gabriel Weibel Blog 버블 정렬 자바 구현
public class BubbleSort { public static void main(String[] args) { int arr[] = {23, 5, 35, 66, 11, 77, 24, 34, 54}; BubSort bs = new BubSort(); bs.bubbleSort(arr); for (int i = 0; i < arr.length; i++) { System.out.printf(" %d", arr[i]); } System.out.println(); } } class BubSort { public void bubbleSort(int arr[]) { int arrSize = arr.length; for (int i = arrSize; i > 1; i--) { for (int j = 1; j < i; j++) { if (arr[j-1] > arr[j]) { int temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; } } } } }
선택 정렬(Selection Sort)
- 전체 원소들 중에서 선택하여 기준 위치에 맞는 원소를 선택하여 자리를 교환하는 방식으로 정렬
- O(N²)
- 버블 정렬보다 두배 빠르다.
출처: Programiz 선택 정렬 자바 구현
public class SelectionSort { public static void main(String[] args) { int arr[] = {2,1,4,5,3,7,6,8}; SelectSort ss = new SelectSort(); ss.selectionSort(arr); for (int i = 0; i < arr.length; i++) { System.out.printf(" %d", arr[i]); } System.out.println(); } } class SelectSort { public void selectionSort(int arr[]) { for (int i = 0; i < arr.length; i++) { int lowestValueIndex = i; for (int j = i+1; j < arr.length; j++) { if (arr[lowestValueIndex] > arr[j]) { lowestValueIndex = j; } } if (lowestValueIndex != i) { int tempValue = arr[i]; arr[i] = arr[lowestValueIndex]; arr[lowestValueIndex] = tempValue; } } } }
학습 교재
'자료구조' 카테고리의 다른 글
순차 검색(Linear Search), 이진 검색(Binary Search) (0) 2021.03.26 삽입 정렬(Insertion Sort), 퀵 정렬(Quick Sort) (0) 2021.03.26 깊이 우선 탐색(DFS), 너비 우선 탐색(BFS) (0) 2021.03.19 그래프(Graph)의 종류, 용어, 구현 (0) 2021.03.19 힙(Heap) (0) 2021.03.17