[C++] Basic sorting algorithm

Basic sorting algorithm ( Selection, Bubble, Insertion)


아래 알고리즘들은 오름차순을 기준으로 함

선택 정렬 (Selection Sort)

선택 정렬 알고리즘

최소값 탐색 후 가장 앞 자리로 옮기며 정렬하는 알고리즘

  1. 주어진 리스트 중에 최소값을 찾는다.
  2. 그 값을 맨 앞에 위치한 값과 교체한다.
  3. 맨 처음 위치를 뺀 나머지 리스트를 같은 방법으로 교체한다.

선택 정렬 C++ 코드

#include <iostream>
#include <vector>
 
using namespace std;
 
void selectionSort(vector<int> &list, int n) {
	int temp;
	for (int i = 0; i < n - 1; i++) {
		int indexMin = i;
		for (int j = i + 1; j < n; j++) {
			if (list[j] < list[indexMin])
				indexMin = j;
		}
		//swap
		temp = list[indexMin];
		list[indexMin] = list[i];
		list[i] = temp;
	}
}
 
int main() {
	int n;
	cin >> n;
	vector<int> list(n);
	for (int i = 0; i < n; i++)
		cin >> list[i];
 
	selectionSort(list, n);
 
	for (int i = 0; i < n; i++)
		cout << list[i]<<" ";
 
	return 0;
}

버블 정렬 (Bubble Sort)

버블 정렬 알고리즘

서로 인접한 두 원소를 검사하여 정렬하는 알고리즘

  1. i 번째 요소와 i + 1 번째 요소와 비교
  2. i 번째 요소가 i + 1 번째 요소보다 크면 둘이 swap
  3. 1~2 과정을 i + 1 = n 이 될 때까지 반복
  4. n을 1감소하고 1~3 과정 반복
  5. n = 1 되면 끝

버블 정렬 c++ 코드

#include <iostream>
#include <vector>
 
using namespace std;
 
void BubbleSort(vector<int> &list, int n) {
	int temp;
	bool swapped;
	for (int i = 0; i < n - 1; i++) {
		swapped = false;
		for (int j = 0; j < n - i - 1; j++) {
			if (list[j] > list[j + 1]) {
				//swap
				temp = list[j];
				list[j] = list[j + 1];
				list[j + 1] = temp;
				swapped = true;
			}
		}
		//버블 정렬 최적화 코드
		if (swapped == false)break;
	}
}
 
int main() {
	int n;
	cin >> n;
	vector<int> list(n);
	for (int i = 0; i < n; i++)
		cin >> list[i];
 
	BubbleSort(list, n);
 
	for (int i = 0; i < n; i++)
		cout << list[i]<<" ";
 
	return 0;
}

삽입 정렬 (Insertion Sort)

사람이 손안의 카드를 정렬하는 방법과 유사

삽입 정렬 알고리즘

자신의 위치를 찾아 삽입하면서 완성하는 알고리즘

  1. 두 번째 요소 부터 시작
  2. 자신의 앞에 있는 요소들은 정렬이 되어 있음
  3. 앞에 요소와 하나씩 비교하면서 자신의 위치를 찾아서 삽입
  4. i++

삽입 정렬 c++ 코드

#include <iostream>
#include <vector>
 
using namespace std;
 
 
void insertionSort(vector<int> &list, int n) {
	int key;
	for (int i = 1; i < n; i++) {
		key = list[i];
		int j = i - 1;
		while (j >= 0 && list[j] > key) {
			list[j + 1] = list[j];
			j--;
		}
		list[j + 1] = key;
	}
}
 
int main() {
	int n;
	cin >> n;
	vector<int> list(n);
	for (int i = 0; i < n; i++)
		cin >> list[i];
 
	insertionSort(list, n);
 
	for (int i = 0; i < n; i++)
		cout << list[i]<<" ";
 
	return 0;
}

시간 복잡도 비교

시간 복잡도 비교 https://gmlwjd9405.github.io/2018/05/06/algorithm-insertion-sort.html