알고리즘을 풀 때 주로 stl에서 제공하는 sort 메서드를 사용하기 때문에 퀵 소트를 구현하는 방법을 잊어버리는 경우가 많습니다.
실제 면접에서 퀵 소트를 구현하라는 경우가 적지 않으니 퀵 소트를 구현해보겠습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
// 범위는 [begin, end) | |
void quickSort(int *arr, int begin, int end) | |
{ | |
// 재귀 종료 조건 | |
if (end - begin <= 1) | |
return; | |
int pivot = arr[begin]; // 기준 | |
int left = begin + 1; | |
int right = end - 1; | |
while (1) | |
{ | |
while (left <= right && arr[left] <= pivot) | |
left++; | |
while (left <= right && arr[right] >= pivot) | |
right--; | |
if (left > right) | |
break; | |
swap(arr[left], arr[right]); | |
} | |
swap(pivot, arr[right]); | |
// 반으로 쪼개어 정렬 | |
quickSort(arr, begin, right); | |
quickSort(arr, right + 1, end); | |
} |
반응형
'면접 준비' 카테고리의 다른 글
데이터베이스) DBMS 키 정리 (0) | 2020.06.10 |
---|---|
데이터베이스 쿼리 실행 순서 (2) | 2020.06.07 |
삽입 정렬(Insertion Sort) 구현 (0) | 2019.10.06 |
선택 정렬(Selection Sort) 구현 (0) | 2019.10.06 |
머지 소트(Merge Sort) STL 없이 구현 (0) | 2019.07.30 |