code from chapter 4 in javascript
This commit is contained in:
11
04_quicksort/01_loop_sum.js
Normal file
11
04_quicksort/01_loop_sum.js
Normal file
@@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
function sum(arr) {
|
||||
let total = 0;
|
||||
for (let x = 0; x < arr.length; x++) {
|
||||
total += arr[x];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
console.log(sum([1, 2, 3, 4])) // 10
|
||||
10
04_quicksort/02_recursive_sum.js
Normal file
10
04_quicksort/02_recursive_sum.js
Normal file
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
function sum(list) {
|
||||
if (list.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
return list[0] + sum(list.slice(1));
|
||||
}
|
||||
|
||||
console.log(sum([1, 2, 3, 4])) // 10
|
||||
10
04_quicksort/03_recursive_count.js
Normal file
10
04_quicksort/03_recursive_count.js
Normal file
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
function count(list) {
|
||||
if (list.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
return 1 + count(list.slice(1));
|
||||
}
|
||||
|
||||
console.log(count([0, 1, 2, 3, 4, 5])); // 6
|
||||
11
04_quicksort/04_recursive_max.js
Normal file
11
04_quicksort/04_recursive_max.js
Normal file
@@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
function max(list) {
|
||||
if (list.length === 2) {
|
||||
return list[0] > list[1] ? list[0] : list[1];
|
||||
}
|
||||
let sub_max = max(list.slice(1));
|
||||
return list[0] > sub_max ? list[0] : sub_max;
|
||||
}
|
||||
|
||||
console.log(max([1, 5, 10, 25, 16, 1])); // 25
|
||||
18
04_quicksort/05_quicksort.js
Normal file
18
04_quicksort/05_quicksort.js
Normal file
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
function quicksort(array) {
|
||||
if (array.length < 2) {
|
||||
// base case, arrays with 0 or 1 element are already "sorted"
|
||||
return array;
|
||||
} else {
|
||||
// recursive case
|
||||
let pivot = array[0];
|
||||
// sub-array of all the elements less than the pivot
|
||||
let less = array.slice(1).filter(function(el) { return el <= pivot; });
|
||||
// sub-array of all the elements greater than the pivot
|
||||
let greater = array.slice(1).filter(function(el) { return el > pivot; });
|
||||
return quicksort(less).concat([pivot], quicksort(greater));
|
||||
}
|
||||
}
|
||||
|
||||
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]
|
||||
Reference in New Issue
Block a user