5 Sorting Programs In Python Without Using Libraries - True Gyan

5 Sorting Programs In Python Without Using Libraries

Bubble Sort

n = int(input("Please enter a number for how many number of item sort:\n"))

i = 0

items = []

print("Enter all item for sorting:")

while(i < n):

    user_item = int(input())

    items.append(user_item)

    i = i + 1

print("You given items:\n",items)

def bubble_sort(items):

    # We set swapped to True for run loops

    swapped = True

    while swapped:

        swapped = False

        for i in range(len(items) - 1):

            if items[i] > items[i + 1]:

                # Swap the elements

                items[i],items[i + 1] = items[i + 1], items[i]

                # Set the flag to True so we'll loop again

                swapped = True


bubble_sort(items)

print("Element After bubble_sort : ", items)


Insertion Sort

n = int(input("Please enter a number for how many number of item sort:\n"))
i = 0
items = []
print("Enter all item for sorting:")
while(i < n):
    user_item = int(input())
    items.append(user_item)
    i = i + 1
print("You given items:\n",items)
def insertionsort(items):
    for i in range(1, len(items)):

        key = items[i]

        # Move elements of arr[0..i-1], that are greater than key, 
        # to one position ahead of their current position
        j = i - 1
        while j >= 0 and key < items[j]:
            items[j + 1] = items[j]
            j = j - 1
        items[j + 1] = key
insertionsort(items)
print("Your sorted items:\n")
for i in items:
    print(i, end=' ')


Selection Sort

n = int(input("Please enter a number for how many number of item sort:\n"))
i = 0
items = []
print("Enter all item for sorting:")
while(i < n):
    user_item = int(input())
    items.append(user_item)
    i = i + 1
print("You given items:\n",items)

def selection_sort(items):
    # This value of i corresponds to how many values were sorted
    for i in range(len(items)):
        # Assume first item of the unsorted segment is the smallest
        lowest_value = i
        # This loop iterates over the unsorted items
        for j in range(i + 1, len(items)):
            if items[j] < items[lowest_value]:
                lowest_value = j
        # Swap values of the lowest unsorted element with the first unsorted element
        items[i], items[lowest_value] = items[lowest_value], items[i]

selection_sort(items)
print("Element After selection_sort : ", items)



Merge Sort

n = int(input("Please enter a number for how many number of item sort:\n"))
i = 0
items = []
print("Enter all item for sorting:")
while(i < n):
    user_item = int(input())
    items.append(user_item)
    i = i + 1
print("You given items:\n",items)
def mergeSort(items):
    if len(items) > 1:

        # Finding the mid of the array
        mid = len(items) / 2

        # Dividing the array elements
        left = items[:mid]
        print(left)

        # into 2 halves
        right = items[mid:]

        # Sorting the first half
        mergeSort(left)

        # Sorting the second half
        mergeSort(right)

        i =  0
        j = 0
        k = 0

        # Copy data to temp arrays L[] and R[]
        while i < len(left) and j < len(R):
            if left[i] < right[j]:
                items[k] = left[i]
                i += 1
            else:
                items[k] = right[j]
                j += 1
            k += 1

# Code to print the list


def printList(arr):
    print("Sorted array is:")
    for i in range(len(arr)):
        print(arr[i], end=" ")
    print()

mergeSort(items)
printList(items)



Quick Sort

n = int(input("Please enter a number for how many number of item sort:\n"))
i = 0
items = []
print("Enter all item for sorting:")
while(i < n):
    user_item = int(input())
    items.append(user_item)
    i = i + 1
print("You given items:\n",items)

def partition(NumList, low, high):
    # The pivot element is selected middle element. Some implementations select
    # the first element or the last element. Sometimes the median value becomes
    # the pivot, or a random one. There are many more strategies that can be
    # chosen or created.
    pivot = NumList[(low + high) // 2]
    i = low - 1
    j = high + 1
    while True:
        i += 1
        while NumList[i] < pivot:
            i += 1

        j -= 1
        while NumList[j] > pivot:
            j -= 1

        if i >= j:
            return j

        # If an element at i (on the left of the pivot) is larger than the
        # element at j (on right right of the pivot), then swap them
        NumList[i], NumList[j] = NumList[j], NumList[i]


def quick_sort(items):
    # Create a helper function that will be called recursively
    def _quick_sort(itemss, low, high):
        if low < high:
            # This is the index after the pivot, where our lists are split
            split_index = partition(itemss, low, high)
            _quick_sort(itemss, low, split_index)
            _quick_sort(itemss, split_index + 1, high)

    _quick_sort(items, 0, len(items) - 1)


quick_sort(items)
print("Element After Quick_sort : ", items)


See All Output Like This