Merge Sort Implementation Check

2024/10/7 7:31:40

I am doubtful of my implementation of the merge sort for two cases specifically:

1. If the size of the list is 2, then I have swapped the values if they are not in the ascending order else I have returned them.

2. In the merge function when the list tries to check outside the number of elements in it, I have assigned the greatest number (9999), so that in case of comparison with it always comes false.
Can anyone tell me if the implementation of my merge sort is correct or not? As in sorting is complete, but is the implementation of merge sort exact or is it wrong because of the cases?

Here is my code:

# unsorted LIST
u_list = [3, 6, 8, 1, 4, 7, 2, 12, 45];# Size of the unsorted list
global_size = len(u_list)def foo(temp_list):size_of_list = len(temp_list)# If the size of the list is 1if size_of_list == 1:return temp_list# If the size of the list is 2if size_of_list == 2:if temp_list[0] > temp_list[1]:temp_list[0],temp_list[1] = temp_list[1],temp_list[0]return temp_listelse: return temp_list# If the size of the list is greater than 2                if size_of_list > 2:count = 1i = 0if size_of_list % 2 == 0:mid1 = size_of_list / 2else:mid1 = (size_of_list / 2) + 1mid2 = size_of_list - mid1newlist1 = list()newlist2 = list()for e in temp_list:if count >= mid1 + 1:newlist2.append(e)else:newlist1.append(e)if count == size_of_list:breakcount = count + 1sorted_list = list()return merge(foo(newlist1), foo(newlist2))# Merging all the sorted components
def merge(list1, list2):i = 0j = 0k = 0size_of_list = len(list1) + len(list2)sorted_list = list()while k <= size_of_list - 1:if i == len(list1):list1.append(9999)if j == len(list2):list2.append(9999)if list1[i] < list2[j]:sorted_list.append(list1[i])i = i + 1elif list2[j] < list1[i]:sorted_list.append(list2[j])j = j + 1k = k + 1return sorted_listprint foo(u_list)
Answer

To be honest, I feel very uneasy if I see code like this ;). It may be correct, but my guts feeling sais it's not (what if there are numbers > 9999?). It is more complicated than necessary. The syntax is Python, but you are not using the power of Python.

Here's how I would implement merge sort in Python:

def merge_sort(sequence):if len(sequence) < 2: return sequencemid = int(len(sequence) / 2)left_sequence = merge_sort(sequence[:mid])right_sequence = merge_sort(sequence[mid:])return merge(left_sequence, right_sequence)def merge(left, right):result = []i = j = 0while i < len(left) and j < len(right):if left[i] < right[j]:result.append(left[i])i += 1else:result.append(right[j])j += 1 result += left[i:]result += right[j:]return result
https://en.xdnf.cn/q/118850.html

Related Q&A

How to create a def in python that pick a specific value and then make a new dict like this

myDict ={"key1" : "val1","key2" : "val2","key3" : "val3","key4" : "x","key5" : "x"}I need a def in py…

Inputs required in python on csv files

I have a problem and need to solve it using Pandas/Python. Not sure how to achieve it and would be great if someone help here to build the logic. I have to generate the output file as below: df = pd.Da…

ServiceBusError : Handler failed: tuple object has no attribute get_token

Im getting the below error when i run my code. This code is to requeue the Deadletter messages. Error: Exception has occurred: ServiceBusError Handler failed: tuple object has no attribute get_token. A…

sqlite3.OperationalError: near WHERE: syntax error

I want to update a series of columns Country1, Country2... Country 9 based on a comma delimited string of country names in column Country. Ive programmed a single statement to accomplish this task. cur…

If statement not working correctly in Python 3

This is the start of an RPG I am going to make, and It runs smoothly until I try to change the gender by saying yes or any other of the answers that activate the if statement. Is there something I am f…

pymc3 error. AttributeError: module arviz has no attribute geweke [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

how to prevent duplicate text in the output file while using for loop

I have this code which compares a number to a number(what i called item in my code) in the domain range to see if it is already there. If it its then print to the output file if it is not then only pri…

How to replace \\ with \ without raising an EOL error?

I am reading from a file that contains byte data but when I open the file and store the readline data into a variable it stores it in a string with backslash escapes, So when trying to decode that data…

How to find duplicates in pandas dataframe

Editing. Suppose I have the following series in pandas:>>>p 0 0.0 1 0.0 2 0.0 3 0.3 4 0.3 5 0.3 6 0.3 7 0.3 8 1.0 9 1.0 10 1.0 11 0.2 12 0.2 1…

i have error eol while scanning string literal

i dont know what is the problem im junior on python programer what happened on my code i study but i dnt understand this #fungsi coveragedef coverage ():print("[1] Kota Besar)print("[2] Kota…