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

Sorting Programs

The document provides implementations of three sorting algorithms: selection sort, insertion sort, and bubble sort. Each algorithm is defined with a function that sorts a given list of numbers and prints the unsorted and sorted lists. The examples demonstrate how each sorting method rearranges the elements in ascending order.

Uploaded by

djo130808
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)
2 views1 page

Sorting Programs

The document provides implementations of three sorting algorithms: selection sort, insertion sort, and bubble sort. Each algorithm is defined with a function that sorts a given list of numbers and prints the unsorted and sorted lists. The examples demonstrate how each sorting method rearranges the elements in ascending order.

Uploaded by

djo130808
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

Selection sort

def selection_sort(list1):
n = len(list1)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if list1[j] < list1[min_idx]:
min_idx = j
list1[i], list1[min_idx] = list1[min_idx], list1[i]
return list1
unsorted_list = [64, 25, 12, 22, 11]
print("unsorted list: ", unsorted_list)
sorted_list = selection_sort(unsorted_list)
print("sorted array: ", sorted_list)

Insertion sort
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
numbers = [12, 11, 13, 5, 6]
print("unsorted list :", numbers)
insertion_sort(numbers)
print("sorted list :", numbers)

Bubble sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
numbers = [64, 34, 25, 12, 22, 11, 90]
print("original list :", numbers)
bubble_sort(numbers)
print("sorted list :", numbers)

You might also like