Question

convert code from python to cpp L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]   #Merging function def merge(M,N): merging_list = []...

convert code from python to cpp

L = [2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3]  

#Merging function
def merge(M,N):
merging_list = []        //create empty list to merge the lists M and N

if not M:                //if M is empty list,
m = 0                //set m = 0
else:
m = len(M)             //otherwise, set m = len(M)
if not N:                //if N is empty list,
n = 0                //set n = 0
else:
n = len(N)             //otherwise, set n = len(N)

(i, j) = (0,0)             //set to indexes i and j as 0

while i+j < m+n:
if i == m:         //if list M is empty, append entire list N to merging_list
merging_list.append(N[j])
j = j+1
elif j == n:         //if list N is empty, append entire list M to merging_list
merging_list.append(M[i])
i = i+1
elif M[i] <= N[j]:         //head of M is smaller, append element from M
merging_list.append(M[i])
i = i+1
elif M[i] > N[j]:        //head of N is smaller, append element from N
merging_list.append(N[j])
j = j+1
  
return(merging_list)         //return the merged list

//Sorting function
def supersort(L, left, right):
if len(L) < 1:             //if list is empty, return 0
return()
      
Forward_sorted_list = []     //list for storing left to right traversals
Backward_sorted_list = []     //#list for storing right to left traversals

//FORWARD SELECTION:
//#traversing from left to right
current_highest = L[0]                     //#set the first element as the current number
Forward_sorted_list.append(current_highest)        //#add current element to the list Forward_sorted_list
for i in range(left+1, right):                 //#traverse all elements from left to right
if L[i] >= current_highest:                //#if the number is greater than or equal to current_highest,
current_highest = L[i]                 //#set that number as the current_highest
Forward_sorted_list.append(current_highest)    //#add it to the list Forward_sorted_list

//#The following step is done to reduce the elements in L as removing an element from a list while working on it is not recommended.
for number in Forward_sorted_list:             //#now for all numbers in Forward_sorted_list,
if number in L:                    //if they are in L,
L.remove(number)                   //#remove them from L so we have reduced the list L

  
//BACKWARD SELECTION:
if len(L) > 1:             //it is possible that after left traversal, the list L becomes empty
                   //#thus, in that case we need to check again, if number present, only then proceed for right traversal
//#traversing from right to left
current_highest = L[-1]                //#set the last element as current_highest
Backward_sorted_list.append(current_highest)        //#add current_highest to the list Backward_sorted_list
for i in range(-2, -(len(L)+1), -1):         //#for all numbers starting from second last, till the index -(len(L)+1), go backwards
if L[i] >= current_highest:            //#if the number is greater than or equal to current_highest,
current_highest = L[i]             //#set that number as the current_highest
Backward_sorted_list.append(current_highest)    //#add it to list Backward_sorted_list
  
   //#The following step is done to reduce the elements in L as removing an element from a list while working on it is not recommended.
for number in Backward_sorted_list:             //#now for all numbers in Backward_sorted_list,
if number in L:                    //#if they are in L,
L.remove(number)               //#remove them from L so we have reduced the list L

intermediate_sorted_1 = merge(Forward_sorted_list, Backward_sorted_list) #store merged Forward_sorted_list and Backward_sorted_list in intermediate_sorted_1

mid = len(L)//2                    //find the mid of the list L after left and right traversals
Left_sublist = L[ : mid]                     //create left sublist
Right_sublist = L[mid : ]                     //create right sublist
Mid_list1 = supersort(Left_sublist, 0, len(Left_sublist)) //apply supersort on left sublist
Mid_list2 = supersort(Right_sublist, 0, len(Right_sublist))   //apply supersort on right sublist

intermediate_sorted_2 = merge(Mid_list1, Mid_list2)     //merge left and right sorted sublist

//Display the intermediate states of the lists to trace the algorithm (commented):
  
//#print("\nThe list L is: ", L)
//#print("The list forward sorted list is: ", Forward_sorted_list)
//#print("The list backward sorted is: ", Backward_sorted_list)
//#print("The intermediate merged list from forward and backward sorted list is: ", intermediate_sorted_1)
//#print("The intermediate merged list from merging left and right sublist is: ", intermediate_sorted_2)
return(merge(intermediate_sorted_1, intermediate_sorted_2))

print("\n\nThe input list is: ", L)
//#Call to the sorting function
sorted_list = supersort(L, 0, len(L))  
print("\nThe sorted list is: ", sorted_list)

Homework Answers

Answer #1

#include<iostream>

#include<lsit>

#include<vector>

int main()

{

std::list<int>M;

std::list<int>N;

std::<list>::iterator it1;

std::<list>::iterator it2;

it1=M.begin();

it2=N.begin();

if(!M.empty())

m=M.size();

else

m=0;

if(!N.empty())

n=N.size();

else

n=0;

N.merge(M);

for(auto it=N.begin();it!=N.end();++it)

cout<<*it<<" ";

std::list<int>forward;

std::list<int>backward;

std::list<int>L={2,7,4,19,45,16,9,13,8,69,55,11,23,98,14,5,1,3};

L.sort():

for(auto it3=L.begin();it3!=L.end();++it3)

cout<<' '<<*it3;

return 0;

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Write a function intersect(L, M) that consumes two sorted lists of distinct integers L and M,...
Write a function intersect(L, M) that consumes two sorted lists of distinct integers L and M, and returns a sorted list that contains only elements common to both lists. You must obey the following restrictions: No recursion or abstract list functions, intersect must run in O(n) where n is the combined length of the two parameters. Example: intersect([3, 7, 9, 12, 14], [1, 2, 5, 7, 10, 11, 12]) => [7, 12] Hint: As the title hints at, you are...
Use Python to Complete the following on a single text file and submit your code and...
Use Python to Complete the following on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples: Sum all the items in a list. Multiply all the items in a list. Get the largest number from a list. Get the smallest number from a list. Remove duplicates from a list. Check a list is empty or not. Clone or copy...
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    //...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    // STEP 1 -- Make sorting methods generic    ///////////////////////////////////////////////       /**    * Re-orders the contents given array using the insertion sort algorithm.    *    * @param data The array to be sorted.    */    //TODO: Make me generic to work on any kind of Comparable data!    public static void insertionSort(int[] data)    {        int insert; // temporary...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Restricted structures such as stack and queue are fast, but they do not support access in...
Restricted structures such as stack and queue are fast, but they do not support access in the key field mode. Group of answer choices True False Big O analysis evaluates an algorithm based on its _________ performance. Group of answer choices A. average-case B. best-case C. worst-case Which of the following algorithms is the fastest in speed? Group of answer choices A. Polynomial time algorithm B. Linear time algorithm C. Exponential time algorithm The following code gives an implementation of...
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...