
Different Sorting Methodologies in Python β Complete Guide
π Different Sorting Methodologies in Python β Complete Guide Hi All, In this blog, Iβll explain the different sorting algorithms I learned, including their working, code, and complexity . π What is Sorting? Sorting is the process of arranging elements in a specific order: Ascending (small β large) Descending (large β small) π§ 1. Bubble Sort π‘ Idea: Repeatedly compare adjacent elements and swap if needed. π» Code: 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 β‘ Complexity: Time: O(nΒ²) Space: O(1) π§ 2. Selection Sort π‘ Idea: Find the minimum element and place it at the beginning. π» Code: def selection_sort ( arr ): n = len ( arr ) for i in range ( n ): min_idx = i for j in range ( i + 1 , n ): if arr [ j ] < arr [ min_idx ]: min_idx = j arr [ i ], arr [ min_idx ] = arr [ min_idx ], arr [ i ] return arr β‘ Complexity: Time: O(nΒ²) Space: O(1) π§ 3. In
Continue reading on Dev.to Tutorial
Opens in a new tab



