퀵 정렬(quick sort)
function quickSort(array, left = 0, right = array.length - 1) {
if (array.length < 1) {
return []
}
const pivotIndex = partition(array, left, right - 1)
if (left < pivotIndex - 1) quickSort(array, left, pivotIndex - 1) // 기준 왼쪽 부분 재귀
if (pivotIndex + 1 < right) quickSort(array, pivotIndex + 1, right) // 기준 오른쪽 부분 재귀
return array
}
function swap(arr, a, b) {
const temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
}
function partition(array, left, right) {
const pivotIndex = right + 1
const pivot = array[pivotIndex]
while (left <= right) {
// 왼쪽, 오른쪽 수를 피벗과 비교해 다음 수로 이동
while (array[left] < pivot) left++
while (array[right] > pivot) right--
if (left <= right) {
swap(array, left, right) // 서로 스왑
left++
right--
}
}
swap(array, left, pivotIndex) // 피벗값과 left와 right가 만난 값을 스왑
return left
}
quickSort([4, 1, 7, 6, 3, 8, 2, 5]) // [1,2,3,4,5,6,7,8]Last updated