Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Other functions: const fold_left = function (f, base, ls) { if (ls.size == 0) { return base; } // Write the recursive fold_left call return

Other functions:

const fold_left = function (f, base, ls) {

if (ls.size == 0) {

return base;

}

// Write the recursive fold_left call

return fold_left(f, f(base, ls.first()), ls.shift());

};

const map = (g, ls) => fold_left((acc, value) => acc.push(g(value)), List([]), ls);

const filter = (g, ls) => fold_left((acc, value) => g(value) ? acc.push(value) : acc, List([]), ls);

const partition = (g, ls) => List([filter(g, ls), filter(value => !g(value), ls)]);

/* TASK 5 (15pts):

Now that we have all the building blocks, our final task is to implement a

naive version of quicksort.

Here's an explanation of how quicksort works:

Given a list to sort, pick an element x from the list as a pivot. Now the

remainder of the list is divided into two partitions, one partition with all

the elements <= x, the other partition with all the elements > x. Now

recursively call the quicksort algorithm on each partition and then combine

the two partitions again (don't forget to put the pivot back in as well!).

The base case for the recursion would be when there's only 1 or 0 elements

in a partition, in which case the partition is returned as is. (The inductive

case is described above.)

Quicksort looks pretty scary in most languages, but with the help of

functional programming, it should only be a few lines of code.

For simplicity, pick the first element of the list as the pivot and the

remaining list as the list to be partitioned.

*/

function quicksort(ls) {

if (ls.size <= 1) {

return ls;

}

const pivot = ls[0];

const [left, right] = partition(x => x <= pivot, ls.slice(1));

return quicksort(left).concat([pivot], quicksort(right));

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Big Data Concepts, Theories, And Applications

Authors: Shui Yu, Song Guo

1st Edition

3319277634, 9783319277639

More Books

Students also viewed these Databases questions

Question

What is Working Capital ? Explain its types.

Answered: 1 week ago