forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise_2.js
43 lines (37 loc) · 1.02 KB
/
Exercise_2.js
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
//Time, space complexity will be O(nlogn) and worst case will be O(n*n)
function swap(array, leftIndex, rightIndex){
let temp = array[leftIndex];
array[leftIndex] = array[rightIndex];
array[rightIndex] = temp;
}
function partition(array, leftIndex, rightIndex) {
let a = array
let start = leftIndex
let end = rightIndex
let pivot = a[Math.floor((start + end) / 2)]
while (start <= end ) {
while (a[start] < pivot) {
start++
}
while (a[end] > pivot) {
end--
}
if( start <= end) {
swap(a, start, end)
start++
end--
}
}
return start
}
function quickSort(array, leftIndex, rightIndex) {
if (leftIndex < rightIndex) {
let index = partition(array, leftIndex, rightIndex)
quickSort(array, leftIndex, index-1)
quickSort(array, index+1, rightIndex)
}
return array
}
var unsortedArray = [1,10,8,9,7,2]
var sortedArray = quickSort(unsortedArray, 0, unsortedArray.length - 1)
console.log(sortedArray)