Sorting Algorithms in Python? - with practical example

Sorting algorithms are essential tools in computer science to organize data in a specific order. In Python, there are various sorting algorithms available that can be used to arrange elements in a list in a particular sequence. Two common sorting algorithms in Python are Bubble Sort and Merge Sort. Example 1: Bubble Sort Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted. Step 1: Compare the first two elements of the list. If the first element is greater than the second element, swap them. Step 2: Move to the next pair of elements and repeat the comparison and swapping process until the end of the list. Step 3: Repeat steps 1 and 2 until no more swaps are needed, indicating that the list is sorted.
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]
    return arr

arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print(sorted_arr)

Example 2: Merge Sort Merge Sort is a divide and conquer algorithm that divides the input list into two halves, recursively sorts the sublists, and then merges the sorted sublists to produce the final sorted list. Step 1: Divide the input list into two halves. Step 2: Recursively sort the two halves. Step 3: Merge the sorted halves to produce the final sorted list.
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

arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = merge_sort(arr)
print(sorted_arr)

By understanding and implementing these sorting algorithms in Python, you can efficiently manage and organize data in a systematic manner.

Comments

Popular posts from this blog

What are the different types of optimization algorithms used in deep learning?

What are the different evaluation metrics used in machine learning?

What is the difference between a module and a package in Python?