Skip to content

Commit 040cfe5

Browse files
author
Kevin Nguyen
committed
code from chapter 4 in javascript
1 parent df27753 commit 040cfe5

File tree

5 files changed

+60
-0
lines changed

5 files changed

+60
-0
lines changed

04_quicksort/01_loop_sum.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
'use strict';
2+
3+
function sum(arr) {
4+
let total = 0;
5+
for (let x = 0; x < arr.length; x++) {
6+
total += arr[x];
7+
}
8+
return total;
9+
}
10+
11+
console.log(sum([1, 2, 3, 4])) // 10

04_quicksort/02_recursive_sum.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
'use strict';
2+
3+
function sum(list) {
4+
if (list.length === 0) {
5+
return 0;
6+
}
7+
return list[0] + sum(list.slice(1));
8+
}
9+
10+
console.log(sum([1, 2, 3, 4])) // 10

04_quicksort/03_recursive_count.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
'use strict';
2+
3+
function count(list) {
4+
if (list.length === 0) {
5+
return 0;
6+
}
7+
return 1 + count(list.slice(1));
8+
}
9+
10+
console.log(count([0, 1, 2, 3, 4, 5])); // 6

04_quicksort/04_recursive_max.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
'use strict';
2+
3+
function max(list) {
4+
if (list.length === 2) {
5+
return list[0] > list[1] ? list[0] : list[1];
6+
}
7+
let sub_max = max(list.slice(1));
8+
return list[0] > sub_max ? list[0] : sub_max;
9+
}
10+
11+
console.log(max([1, 5, 10, 25, 16, 1])); // 25

04_quicksort/05_quicksort.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
function quicksort(array) {
4+
if (array.length < 2) {
5+
// base case, arrays with 0 or 1 element are already "sorted"
6+
return array;
7+
} else {
8+
// recursive case
9+
let pivot = array[0];
10+
// sub-array of all the elements less than the pivot
11+
let less = array.slice(1).filter(function(el) { return el <= pivot; });
12+
// sub-array of all the elements greater than the pivot
13+
let greater = array.slice(1).filter(function(el) { return el > pivot; });
14+
return quicksort(less).concat([pivot], quicksort(greater));
15+
}
16+
}
17+
18+
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]

0 commit comments

Comments
 (0)