0% found this document useful (0 votes)
2 views3 pages

Merge Sort Code

The document contains Python code implementations for two sorting algorithms: Merge Sort and Quick Sort. Each algorithm includes functions to sort a list of integers input by the user. The Merge Sort function recursively divides the list and merges sorted sublists, while the Quick Sort function uses a pivot to partition the list and recursively sorts the partitions.

Uploaded by

m83675680
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Merge Sort Code

The document contains Python code implementations for two sorting algorithms: Merge Sort and Quick Sort. Each algorithm includes functions to sort a list of integers input by the user. The Merge Sort function recursively divides the list and merges sorted sublists, while the Quick Sort function uses a pivot to partition the list and recursively sorts the partitions.

Uploaded by

m83675680
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Merge Sort Code

def mergesort(list1):

if len(list1)>1:

mid=len(list1)//2

left_list=list1[:mid]

right_list=list1[mid:]

mergesort(left_list)

mergesort(right_list)

i=0

j=0

k=0

while i<len(left_list) and j<len(right_list):

iIf left_list[i]<right_list[j]:

list1[k]=left_list[i]

i=i+1

k=k+1

else:

list1[k]=right_list[j]

j=j+1

k=k+1

while i<len(left_list):

list1[k]=left_list[i]

i=i+1

k=k+1

while i<len(left_list):

lList1[k]=right_list[j]

j=j+1

k=k+1

num = int (input(“how many elements you want in list:”))

list1=[int (input())for x in range(num)]


merge sort(list1)

print(“sorted list:”,list1)

Quick Sort Code

def pivot_place(list1,first,last):

pivot=list1[last]

left=first

right=last-1

while True:

while left<=right and list1[left]<=pivot:

left=left+1

while left<=right and list1[right]>=pivot:

right=right-1

if right<left:

break

else:

list1[left],list1[right]=list1[right],list1[left]

list1[last],list1[left]=list1[left],list1[last]

return left

def quicksort(list1,first,last):

if first<last:

p=pivot_place(list1,first,last)

quicksort(list1,first,p-1)

quicksort(list1,p+1,last)

num=int(input("How many elements do you want in the list:"))

list1=[int(input()) for x in range(num)]

n=len(list1)

quicksort(list1,0,n-1)

print(list1)

You might also like