All Popular Sorting Algorithms in Python

Here are Some Sorting Algorithms that are basically implemented in python



Bubble Sort:

      
def bubble_sort(lst):
    length = len(lst) - 1
    sorted = False
    while not sorted:
        sorted = True
        for i in range(length):
            if lst[i] > lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
                sorted = False
    return lst
print(bubble_sort([7, 10, 4, 3, 20, 15]))

Insertion Sort:

  
def insertion_sort(lst):
    for i in range(1,len(lst)):
        val_to_sort = lst[i]
        while lst[i-1] > val_to_sort and i > 0:
            lst[i-1],lst[i] = lst[i],lst[i-1]
            i-=1
    return lst
print(insertion_sort([9,8,7,6,5,4,3,2,1]))

Merge Sort:

def merge_sort(arr):
    if len(arr) <= 1:
        return

    mid = len(arr)//2

    left = arr[:mid]
    right = arr[mid:]
    # print(left,right)
    merge_sort(left)
    merge_sort(right)

    merge_two(left, right, arr)

def merge_two(a,b,arr):
    len_a = len(a)
    len_b = len(b)

    i = j = k = 0

    while i < len_a and j < len_b:
        if a[i] <= b[j]:
            arr[k] = a[i]
            i+=1
        else:
            arr[k] = b[j]
            j+=1
        k+=1

    while i < len_a:
        arr[k] = a[i]
        i+=1
        k+=1

    while j < len_b:
        arr[k] = b[j]
        j+=1
        k+=1

array = [9,8,7,4,5,6,3,2,1]
merge_sort(array)
print(array)

Quick Sort

def quick_sort(sequence):
    length = len(sequence)
    if length <=1:
        return sequence
    else:
        pivot = sequence.pop()
        items_greater = []
        items_lower = []
        for item in sequence:
            if item > pivot:
                items_greater.append(item)
            else:
                items_lower.append(item)
    return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)
print(quick_sort([9,8,7,6,5,4,3,2,1]))

Selection Sort:


def selection_sort(lst):
    n = len(lst)-1
    for i in range(n):
        mini_value = i
        for j in range(i+1,n+1):
            if lst[j] < lst[mini_value]:
                mini_value = j
        if mini_value !=i:
            lst[mini_value],lst[i] = lst[i],lst[mini_value]
    return lst
print(selection_sort([9,8,7,6,5,4,3,2,1]))


Post a Comment

0 Comments