Thanks to visit codestin.com
Credit goes to flexiple.com

Flexiple Logo
  1. Home
  2. Blogs
  3. Python
  4. How to sort a list in python without the sort function

How to sort a list in python without the sort function

Author image

Harsh Pandey

Software Developer

Published on Tue Mar 26 2024

Introduction:

Sorting a list in Python is a common task, and the built-in sort() function is the go-to method. But did you know that you can also sort a list without using the sort() function? In this blog, we will explore alternative methods to sort a list in Python. By the end, you'll have a deeper understanding of different sorting techniques and their implementations, empowering you to sort lists efficiently in various scenarios.

Sorting Techniques

Bubble Sort Algorithm:

The Bubble Sort algorithm is simple and easy to understand. It compares neighbouring elements in the list and swaps them if they are in the wrong order. This process is repeated until the list is completely sorted. While Bubble Sort is straightforward, it may not be the best choice for sorting large lists.

Example:

def bubble_sort(lst):

    n = len(lst)
    for i in range(n):
        for j in range(0, n - i - 1):
            if lst[j] > lst[j + 1]:
                lst[j], lst[j + 1] = lst[j + 1], lst[j]

Selection Sort Algorithm:

The Selection Sort algorithm finds the smallest element in the unsorted part of the list and moves it to the beginning. It then continues this process for the remaining unsorted elements until the entire list is sorted. Although Selection Sort can be more efficient than Bubble Sort, it still may not be the best choice for large lists.

Example:

def selection_sort(lst):
    n = len(lst)
    for i in range(n):
        min_index = i
        for j in range(i + 1, n):
            if lst[j] < lst[min_index]:
                min_index = j
        lst[i], lst[min_index] = lst[min_index], lst[i]

Insertion Sort Algorithm:

The Insertion Sort algorithm builds the sorted list one element at a time. It efficiently places each element in its proper position by comparing it with the elements already sorted. Insertion Sort is often used for small or nearly sorted lists.

Example:

def insertion_sort(lst):

    for i in range(1, len(lst)):
        key = lst[i]
        j = i - 1
        while j >= 0 and key < lst[j]:

            lst[j + 1] = lst[j]

            j -= 1
        lst[j + 1] = key

By understanding these sorting algorithms, you can choose the most suitable one for your specific list and sorting requirements.

Quick Sort Algorithm:

Quick Sort is a highly efficient sorting algorithm that follows the Divide and Conquer approach. It works by selecting a pivot element from the list and partitioning the other elements into two sub-lists: those less than the pivot and those greater than the pivot. The sub-lists are then recursively sorted using Quick Sort. This process continues until the entire list is sorted. Quick Sort is known for its fast average-case performance and is widely used in practice.

Example:

def quick_sort(lst):
    if len(lst) <= 1:
        return lst
    else:
        pivot = lst[0]
        lesser = [x for x in lst[1:] if x < pivot]
        greater = [x for x in lst[1:] if x >= pivot]
        return quick_sort(lesser) + [pivot] + quick_sort(greater)

Merge Sort Algorithm:

Merge Sort is another Divide and Conquer algorithm that works by dividing the list into two halves and recursively sorting each half. Afterwards, it merges the sorted halves to obtain the final sorted list. Merge Sort has a stable time complexity of O(n log n) for both the average and worst-case scenarios, making it a reliable choice for sorting large lists.

Example:

def merge_sort(lst):
    if len(lst) > 1:
        mid = len(lst) // 2
        left_half = lst[:mid]
        right_half = lst[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]:
                lst[k] = left_half[i]
                i += 1
            else:
                lst[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            lst[k] = left_half[i]
            i += 1
            k += 1

        while j < len(right_half):
            lst[k] = right_half[j]
            j += 1
            k += 1

Heap Sort Algorithm:

Heap Sort uses a special data structure called a heap to sort elements in the list. It builds a max-heap or min-heap (depending on the desired order) from the list elements. The root of the heap represents the largest or smallest element, which is then swapped with the last element. The heap is reduced in size, and the process repeats until the list is sorted. Heap Sort has a time complexity of O(n log n) and is often used for sorting large data sets.

Example:

import heap

def heap_sort(lst):
    heapq.heapify(lst)
    sorted_list = [heapq.heappop(lst) for _ in range(len(lst))]
    lst[:] = sorted_list

Performance Considerations

When sorting a list in Python without the built-in sort() function, performance is crucial. Each method's efficiency depends on its time complexity, showing how sorting time grows with list size. Consider these performance aspects for popular sorting algorithms: Bubble Sort, Insertion Sort, Selection Sort, Quick Sort, Merge Sort, and Heap Sort.

Quick Sort and Merge Sort typically perform well with an average time complexity of O(n log n). However, Bubble Sort and Selection Sort have O(n^2) complexities, making them less efficient for large lists. Heap Sort is also O(n log n) but requires less memory due to in-place sorting.

Conclusion:

Sorting a list in Python is a fundamental skill, and knowing different sorting techniques gives you more options to tackle sorting challenges. Whether you choose the sorted() function, Bubble Sort, Insertion Sort, Selection Sort, Quick Sort, Merge Sort, or Heap Sort, each method has its use cases and performance considerations. By understanding these methods, you can become a more versatile Python programmer, capable of efficiently sorting lists in various scenarios.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.