0% found this document useful (0 votes)
2 views

sorting_algorithms

The document provides Python implementations of three sorting algorithms: bubble sort, insertion sort, and merge sort. Each function sorts an array in ascending order using its respective algorithm. Example usage is included to demonstrate how to apply these sorting functions to a sample data array.

Uploaded by

heian.6971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

sorting_algorithms

The document provides Python implementations of three sorting algorithms: bubble sort, insertion sort, and merge sort. Each function sorts an array in ascending order using its respective algorithm. Example usage is included to demonstrate how to apply these sorting functions to a sample data array.

Uploaded by

heian.6971
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Sorting Algorithms (Python Code)

def bubble_sort(arr):

n = len(arr)

for i in range(n - 1):

for j in range(n - i - 1):

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1], arr[j]

return arr

def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]

j=i-1

while j >= 0 and key < arr[j]:

arr[j + 1] = arr[j]

j -= 1

arr[j + 1] = key

return arr

def merge_sort(arr):

if len(arr) > 1:

mid = len(arr) // 2

left_half = arr[:mid]

right_half = arr[mid:]
merge_sort(left_half)

merge_sort(right_half)

i=j=k=0

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

if left_half[i] < right_half[j]:

arr[k] = left_half[i]

i += 1

else:

arr[k] = right_half[j]

j += 1

k += 1

while i < len(left_half):

arr[k] = left_half[i]

i += 1

k += 1

while j < len(right_half):

arr[k] = right_half[j]

j += 1

k += 1

return arr

# Example usage
data = [64, 34, 25, 12, 22, 11, 90]

print("Bubble Sort:", bubble_sort(data.copy()))

print("Insertion Sort:", insertion_sort(data.copy()))

print("Merge Sort:", merge_sort(data.copy()))

You might also like