Question: Prolog ( 3 0 Points ) ( NOTE: Below we are using Prolog notation. Variables are Uppercase. Constants are lowercase. ) In class I showed

Prolog (30 Points)
(NOTE: Below we are using Prolog notation. Variables are Uppercase. Constants are lowercase.)
In class I showed how 2 sorted-lists can be merged in a sorted fashion. That means we are so close to implementing merge-sort! We will implement merge-sort below.
Example output:
mergeSort([],L).
L =[]
mergeSort([2],L).
L =[2]
mergeSort([4,2,3,1],L).
L =[1,2,3,4]
mergeSort([5,4,6,2,7,3,1,8],L).
L =[1,2,3,4,5,6,7,8]
Our program will be implemented with 5 predicates:
mergeSort/2: which in comes an unsorted list, out goes the sorted list.
merge/3: which merges the
split2ways/3:
insertIn1/5 and insertIn2/5:
So let us go!
Finish mergeSort/2:
mergeSort([],[]) :-!.%% Base case when list is empty
mergeSort([X],[X]) :-!.%% Base case when list has only 1 item
%% YOUR CODE TO HANDLE GENERAL CASE
%%(1) Split the in coming list into 2 sublists
%%(2) Recursively sort both lists
%%(3) Merge both lists into the output list
Here is all the code for merge/3.
(This is all of it, there is nothing else to add.)
merge([],L,L).
merge(L,[],L).
merge([F0|R0],[F1|R1],[F0|L]) :-
(F0< F1),
merge(R0,[F1|R1],L).
merge([F0|R0],[F1|R1],[F1|L]) :-
(F0>= F1),
merge([F0|R0],R1,L).
Here is all the code for split2ways/3.
(This is all of it, there is nothing else to add.)
split2ways(Original,R1,R2) :-
insertIn1(Original,[],[],R1,R2).
You must finish the predicates
insertIn1()(insertIn1/5),
insertIn2()(insertIn2/5),
Both have 5 arguments:
The incoming list
2 lists which hold temporary lists that build the answers
2 lists which will hold the answers
Both predicates will have the same base case (facts) corresponding to when the list to split is empty. It is:
insertIn1([],R1,R2,R1,R2).
It means "When there are no items to split, the temporary lists R1 and R2 are also the answer lists."
Your job is to write the 2 rules that build the temporary lists:
%% YOUR insertIn1 RULE HERE
insertIn1([],R1,R2,R1,R2).%% This is the base case
%% YOUR insertIn2 RULE HERE
insertIn2([],R1,R2,R1,R2).%% This is the base case
What are the remaining 2 rules?
Hints:
Both should separate the list to split into a head and a tail ([H|T]).
Both should build the a list a their respective position
insertIn1/5 should call insertIn2/5
insertIn2/5 should call insertIn1/5

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!