I am working on quick sort using recursion and filter, but the recursion is not working correctly. It returns to the first half of the list sorted + extra (pivot and second half of the list from the last recursion), but second half of the list disappears. Here is my code.
const {
List
} = require('immutable')
const quicksort = function(list) {
if (list.size <= 1) {
return list;
}
pivot = list.last();
part1 = list.pop().filter((x) => x <= pivot);
part2 = list.pop().filter((x) => x > pivot);
return quicksort(part1).concat(list.last(), quicksort(part2));
};
console.log("quicksort: " + quicksort(List([4, 7, 3, 6, 8, 7, 1, 2, 2, 1, 5])));
and it prints out
quicksort: List [ 1, 1, 2, 3, 3, 3, 5 ]
The first time quicksort is called,
part1 is [ 4, 3, 1, 2, 2, 1 ]
pivot is 5
part2 is [ 7, 6, 8, 7 ]
and basically, [ 7, 6, 8, 7 ] just disappears.
I appreciate any insight and advice. Thank you!