70.3k views
5 votes
(10 points) Implement the bubble sort in ML using pattern matching and local function definitions. Show that it works with a few simple examples. A nice description of the bubble sort can be found on Wikipedia. A helpful function for the bubble sort is:

1 Answer

5 votes

Answer:

Follows are the code to this question:

(* defining a bool method issrotd that is an array type which is used for sort the data *)

fun issorted [] = true | issorted [i] = true | issorted (i::j::t) = i <= j andalso issorted(j::t);

(* use swap function for swap the values*)

fun swap [] = [] | swap [i] = [i] | swap (i::j::t) = if (i>j) then j::(swap (i::t))(*use if that swap the value*)

else i::(swap (j::t));(*use else when value is swapped*)

(*call swap to sort the given list*)

fun bubblesort [] = [] | bubblesort x = if (issorted x) then x else bubblesort (swap x);(*use the bubblesort to check the value*)

val e1 = bubblesort [4,5,1,3,2] = [1,2,3,4,5](*use e1 variable to call the bubblesort method and hold its value*)

val e2 = bubblesort [4,5,1] = [1,4,5](*use e2 variable to call the bubblesort method and hold its value*)

Output:

please find the attached file.

Step-by-step explanation:

In the above-given code three methods "issorted, swap, and bubblesort" are defined, in which the "issorted" method is used to check the given value is sort.

If it does not sort, it will go to the "swap" method, that swaps the value and after the swap, it will go to the "bubblesort" method in this method it checks the value is in bubble sort.

At the last step two-variable, "e1 and e2" is defined, that use to call the bubble sort method and hold its return value.

(10 points) Implement the bubble sort in ML using pattern matching and local function-example-1
User RickardP
by
6.0k points