0% found this document useful (0 votes)
12 views1 page

Datactruc- Fahad AS2

The document contains a Python implementation of the merge sort algorithm, which sorts an array by dividing it into halves and merging the sorted halves. It includes a function 'merge_sort' that recursively sorts the array and a 'merge' function that combines the sorted halves. The example demonstrates sorting the array [7, 3, 1, 5, 2, 9] into [1, 2, 3, 5, 7, 9].

Uploaded by

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

Datactruc- Fahad AS2

The document contains a Python implementation of the merge sort algorithm, which sorts an array by dividing it into halves and merging the sorted halves. It includes a function 'merge_sort' that recursively sorts the array and a 'merge' function that combines the sorted halves. The example demonstrates sorting the array [7, 3, 1, 5, 2, 9] into [1, 2, 3, 5, 7, 9].

Uploaded by

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

Fahad hoaidi – 431110934

Assignment 2
def merge_sort(A):

if len(A) > 1:

mid = len(A) // 2

left_half = A[:mid]

right_half = A[mid:]

merge_sort(left_half)

merge_sort(right_half)

merge(A, left_half, right_half)

def merge(A, left_half, right_half):

i=j=k=0

while i < len(left_half) and j < len(right_half):

if left_half[i] < right_half[j]:

A[k] = left_half[i]

i += 1

else:

A[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

A[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

A[k] = right_half[j]

j += 1

k += 1

A = [7, 3, 1, 5, 2, 9]

print("Original :", A)

merge_sort(A)

print("Sorted :", A)

output

Original : [7, 3, 1, 5, 2, 9] Sorted : [1, 2, 3, 5, 7, 9]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy