Day 21: Different Types of Sorting Algorithms in Python

Sorting is a fundamental concept in programming, and python supports multiple sorting techniques. Today, let's explore different sorting algorithms and their implementations!


1?? Bubble Sort (Brute Force)

  • Compares adjacent elements and swaps them if needed
  • Time Complexity: O(n2) (Not efficient for large datasets)

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
print(bubble_sort([64, 35, 27, 10, 21, 22, 90])        

? Simple but inefficient for large lists.


2?? Selection Sort

  • Finds the minimum element and places it at the beginning
  • Time Complexity: O(n2).

def selection_sort(arr):
    n= len(arr)
    for i in range(n):
        min_index = i
        for j in range(i+1,n)
            if arr[j]<arr[min_index]:
                min_index=j
         arr[i], arr[min_index] = arr[min_index],arr[i]
    return arr
print(selection_sort([64, 35, 27, 10, 21, 22, 90]))        

? Better than Bubble Sort, but still O(n2).


3?? Insertion Sort

  • Builds the sorted array one item at a time
  • Time Complexity: O(n2), but efficient for small datasets.

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
print(insertion_sort([64, 35, 27, 10, 21, 22, 90]))        

? Good for nearly sorted data.


4?? Merge Sort (Divide and Conquer)

  • Recursively divides the list into halves and merges them
  • Time Complexity: O(n log n)

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left = arr[:mid]
        right = arr[mid:]

        merge_sort(left)
        merge_sort(right)

        i = j = k = 0
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            arr[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            arr[k] = right[j]
            j += 1
            k += 1

    return arr

print(merge_sort([64, 35, 27, 10, 21, 22, 90]))        

? Great for large datasets. Uses O(n) extra space.


5?? Quick Sort (Divide and Conquer)

  • Picks a pivot, partitions the array, and sorts recursively
  • Time Complexity: O(n log n) (Worst case: O(n2) if poorly implemented)

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2] 
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

print(quick_sort([64, 35, 27, 10, 21, 22, 90]))        

? Faster than Merge Sort in practice. In-place sorting.


6?? Heap Sort

  • It uses a binary heap for sorting
  • Time Complexity: O(n log n)

import heapq

def heap_sort(arr):
   heapq.heapify(arr)
   return [heapq.heappop(arr) for _ in range(len(arr))]

print(heap_sort([64, 35, 27, 10, 21, 22, 90]))        

? Efficient for priority queues


?? Which Sorting Algorithm Should You Use?

? For small datasetsInsertion Sort

? For large datasetsMerge Sort / Quick Sort

? For priority queuesHeap Sort

Which sorting algorithm is your favorite? Let me know in the comments! ????

#Python #SortingAlgorithms #100DaysOfCode

要查看或添加评论,请登录

Sarasa Jyothsna Kamireddi的更多文章

  • Day 26: Basic MySQL Commands

    Day 26: Basic MySQL Commands

    Today, let us explore some fundamental MySQL commands that are essential for database management 1. Creating a Database…

  • Day 25: MySQL Installation

    Day 25: MySQL Installation

    Steps to Install MySQL: ? Download MySQL: Go to MySQL Official Website and choose the appropriate version for your OS…

  • Day 24: Introduction to MySQL

    Day 24: Introduction to MySQL

    Today, let us dive into MySQL, a powerful Relational Database Management System (RDBMS) that helps store and manage…

  • Day 23: Error Handling Best Practice in Python

    Day 23: Error Handling Best Practice in Python

    Proper error handling makes our python code more robust, readable, and maintainable. Here are the best practices to…

  • Day 22: Python Shortcuts to write Cleaner and more Efficient Code

    Day 22: Python Shortcuts to write Cleaner and more Efficient Code

    1. List Comprehensions 2.

  • Day 20: Sorting in Python

    Day 20: Sorting in Python

    Sorting is a fundamental operation in programming. Python provides multiple ways to sort data efficiently.

  • Day 19: Python Coding Challenges

    Day 19: Python Coding Challenges

    Today, let's solve some interesting Python problems! 1?? Find Pairs with Given Sum in an Array Problem: Given an array…

  • Day 18: Python Coding Challenges

    Day 18: Python Coding Challenges

    Today, let's solve some interesting Python problems! 1?? Sum of Digits Until Single Digit Problem: Given a number…

  • Day 17: Python Coding Challenges

    Day 17: Python Coding Challenges

    Let's sharpen our Python skills with some interesting coding challenges! Try solving them and comment your solutions…

  • Day 16: Python Coding Challenges - Sharpen

    Day 16: Python Coding Challenges - Sharpen

    Today, let's practice some interesting Python coding problems to help us think logically and improve our…