Question

Show that mergesort is a stable algorithm by modifiying the algorithm to sort a list of tuples (first and last names) by...

Show that mergesort is a stable algorithm by modifiying the algorithm to sort a list of tuples (first and last names) by their second position. (Modify the merge section to break ties) Modify in python

def mergesort(mlist):
if len(mlist) < 2:
return mlist
else:
mid = len(mlist)//2
return merge( mergesort(mlist[:mid]), mergesort(mlist[mid:]))

# merge two sorted lists
def merge(left, right):
if left == []:
return right
elif right == []:
return left
elif left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
else:
return [right[0]] + merge(left, right[1:])

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python code :

The above python code in question can be modified to sort the list with first name and last name by making it stable sort. The code is as given below with output :

======================================

def mergesort(mlist):

if len(mlist) < 2 :

return mlist

else :

mid = int(len(mlist)/2)

return merge(mergesort(mlist[:mid]), mergesort(mlist[mid:]))

def merge(left, right):

if left == [] :

return right

elif right == [] :

return left

elif left[0][0] < right[0][0]:

return [left[0]] + merge(left[1:], right)

elif left[0][0] > right[0][0]:

return [right[0]] + merge(left, right[1:])

elif left[0][0] == right[0][0] :

if(left[0][1] <= right[0][1]):

return [left[0]] + merge(left[1:], right)

else :

return [right[0]] + merge(left, right[1:])

# sort the list

tuple = [("abc", "aaa"), ("abc", "bbb"), ("abc", "aaa"), ("bcd", "aaa"), ("edfg", "abcd"), ("bc", "aaa")]

print("tuple before sorting : "+ str(tuple))

result = mergesort(tuple)

print("list after sorting : "+ str(result))

===============================================

def mergesort (mlist): if len(mlist) < 2 1 2 return mlist else: mid = int (len (mlist ) /2) return merge(mergesort(mlist[:midThe output of above code :

tuple before sorting : [('abc', 'aaa'), ('abc', 'bbb'), ('abc', 'aaa'), ('bcd', 'aaa'), ('edfg', 'abcd'), ('bc', 'aaa')]
list after sorting : [('abc', 'aaa'), ('abc', 'aaa'), ('abc', 'bbb'), ('bc', 'aaa'), ('bcd', 'aaa'), ('edfg', 'abcd')]

if you have any doubts then you can ask in comment section if you find the solution helpful then upvote the answer. Thank you.

Add a comment
Know the answer?
Add Answer to:
Show that mergesort is a stable algorithm by modifiying the algorithm to sort a list of tuples (first and last names) by...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Here is the code given for this problem: **And please do this in Python** def mergesort(mlist): if len(mlist)<2: ret...

    Here is the code given for this problem: **And please do this in Python** def mergesort(mlist): if len(mlist)<2: return mlist else: mid=len(mlist)//2 return merge(mergesort(mlist[:mid]),mergesort(mlist[mid:])) Problem 1 (30 points) stable merge sort Consider the following unsorted list of integers containing duplicates where the relative position of each duplicated integer in the unsorted list is noted as a subscript. For example, 1, is at a smaller index than 12. The subscript is ignored when comparing two values since it would not actually...

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 pro...

    In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 processes. First half of the array will be sorted by thread 1 and the second half by thread 2. When the threads complete their tasks, the main program will merge the half arrays. You should not waste your time on merge-sort algorithm. Use the merge sort algorithm given below void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j); //right...

  • Python Merge Sort Adjust the following code so that you can create random lists of numbers of lengths 10, 15, and 20. You will run the merge sort 10 times for each length. Record the run time for the...

    Python Merge Sort Adjust the following code so that you can create random lists of numbers of lengths 10, 15, and 20. You will run the merge sort 10 times for each length. Record the run time for the length and then calculate the average time to sort. Finally, compare the average run time for each length to the average time for the Merge Sort. -------------------------------------------- Initial python code: import random import time def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

  • def _merge(lst: list, start: int, mid: int, end: int) -> None: """Sort the items in lst[start:end]...

    def _merge(lst: list, start: int, mid: int, end: int) -> None: """Sort the items in lst[start:end] in non-decreasing order. Precondition: lst[start:mid] and lst[mid:end] are sorted. """ result = [] left = start right = mid while left < mid and right < end: if lst[left] < lst[right]: result.append(lst[left]) left += 1 else: result.append(lst[right]) right += 1 # This replaces lst[start:end] with the correct sorted version. lst[start:end] = result + lst[left:mid] + lst[right:end] def find_runs(lst: list) -> List[Tuple[int, int]]: """Return a...

  • Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace...

    Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void combine(int *a, int low, int high, int mid) {        int i, j, k, c[100000];        i = low;        k = low;        j = mid + 1;        while (i <= mid && j <= high)        {               if (a[i] < a[j])               {                      c[k] = a[i];                      k++;                      i++;               }               else               {                     ...

  • Please give a output Linux/Ubuntu and how to run it (compile) this program ,my assigment is below...

    Please give a output Linux/Ubuntu and how to run it (compile) this program ,my assigment is below : : Merge Sort algorithm using 2 processes a.) Define an integer array of 100 integers. Populate this array with random numbers. You can use int rand(void); function. Do not forget to initialize this function. You will sort the numbers in the array using merge-sort algorithm. In merge sort algorithm the half of the array will be sorted by one process and second...

  • USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list...

    USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list and use a Merge Sort to sort the object by age. Create a class called Person : name and age Create methods that add, and delete Person from the link list Create a method that sorts the persons' objects by age. package mergesort; public class MergeSortExample { private static Comparable[] aux; // auxiliary array for merges public static void sort(Comparable[] a) { aux =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT