-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick Sort.html
More file actions
68 lines (55 loc) · 2.47 KB
/
Quick Sort.html
File metadata and controls
68 lines (55 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 퀵 정렬 O(N * logN) - 특정한 값을 기준으로 큰 숫자와 작은 숫자를 서로 교환한 뒤에 배열을 반으로 나눕니다.
// 기준 값이 존재합니다. -> 피벗(Pivot)
// 대표적인 '분할 정복'알고리즘
// 이미 정렬이 되어 있는경우 or 거의 정렬이 되어 있는경우, 시간 복잡도 O(N^2) - 최악의 경우
// 예시
// 3(기준) 7(!) 8 1 5 9 6 10 2(!) 4
// ->(3보다 큰 값을 찾아감)
// (3보다 작은 값을 찾아감)<-
// 3(기준) 2 8 1 5 9 6 10 7 4 (7 <-> 2)
// 3(기준) 2 8(!) 1(!) 5 9 6 10 7 4
// 3(기준) 2 1 8 5 9 6 10 7 4 (8 <-> 1)
// 3(기준) 2 1(!) 8(!) 5 9 6 10 7 4 (엇갈림 - 큰값의 인덱스가 더 뒤에 존재)
// 1(기준) 2 3(반) 8(기준) 5 9 6 10 7 4 (3 <-> 1)
// 3을 기준으로 왼쪽은 3보다 작고, 오른쪽은 3보다 큽니다.
let array = [10, 1, 5, 8, 7, 6, 4, 3, 2, 9];
let number = 10;
function quickSort(array, start, end) {
if (start >= end) return; // 원소가 1개인 경우
let key = start; // 키는 첫번째 원소
let i = start + 1;
let j = end;
let temp;
while (i <= j) { // 엇갈릴 때까지 반복, i > j
while (array[i] <= array[key] && i <= end) i++; // 키 값보다 큰 값을 만날 때까지 i > key
while (array[j] >= array[key] && j > start) j--; // 키 값보다 작은 값을 만날 때까지 i < key
if (i > j) { // 현재 엇갈린 상태면 키 값과 교체
temp = array[j];
array[j] = array[key];
array[key] = temp;
} else { // 엇갈리지 않았다면 i 와 j를 교체
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
quickSort(array, start, j - 1);
quickSort(array, j + 1, end);
}
quickSort(array, 0, number - 1) // 0 ~ 9
for (i = 0; i < 10; i++) {
console.log(array[i]);
}
</script>
</body>
</html>