Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Sorting Lists in Python without the Sort Function

Learn how to sort lists in Python using various techniques, including bubble sort, insertion sort, and merge sort. This guide provides a step-by-step explanation of each method, along with code snippe …


Updated June 24, 2023

Learn how to sort lists in Python using various techniques, including bubble sort, insertion sort, and merge sort. This guide provides a step-by-step explanation of each method, along with code snippets and explanations. Sorting Lists in Python without the Sort Function

Sorting Lists in Python without the Sort Function is an essential concept that allows developers to manipulate data in their applications. In this article, we will explore how to sort lists in Python using various techniques, while avoiding the built-in sort() function.

Definition of Sorting a List

Before diving into the implementation details, let’s define what sorting a list means:

Sorting a list: The process of arranging elements within an array or list in ascending or descending order based on specific criteria (e.g., numerical values or string lengths).

Step-by-Step Explanation: Bubble Sort

Bubble sort is a simple sorting technique that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Code Snippet 1: Bubble Sort Implementation

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

# Example usage:
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = bubble_sort(numbers)
print(sorted_numbers)  # Output: [11, 12, 22, 25, 34, 64, 90]

How it Works

  1. The outer loop iterates over the list, starting from the first element and ending at the second-to-last element.
  2. The inner loop compares adjacent elements within the current range (i.e., lst[j] and lst[j+1]) and swaps them if they are in the wrong order (lst[j] > lst[j+1]).
  3. Repeat steps 1-2 until the list is sorted.

Step-by-Step Explanation: Insertion Sort

Insertion sort is a simple sorting algorithm that works much like the process of inserting cards into an empty pile. It iterates through the list one item at a time, inserting each item into its proper position within the already-sorted portion of the list.

Code Snippet 2: Insertion Sort Implementation

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

# Example usage:
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = insertion_sort(numbers)
print(sorted_numbers)  # Output: [11, 12, 22, 25, 34, 64, 90]

How it Works

  1. The outer loop iterates over the list, starting from the second element and ending at the last element.
  2. For each element (key = lst[i]), the inner loop compares it with the previous elements in the sorted portion of the list (lst[j]) until a suitable position is found.
  3. Once the correct position is determined, insert the key into that position.

Step-by-Step Explanation: Merge Sort

Merge sort is a divide-and-conquer algorithm that splits the list into smaller sublists, sorts them individually, and then merges them together in sorted order.

Code Snippet 3: Merge Sort Implementation

def merge_sort(lst):
    if len(lst) <= 1:
        return lst
    mid = len(lst) // 2
    left_half = merge_sort(lst[:mid])
    right_half = merge_sort(lst[mid:])
    return merge(left_half, right_half)

def merge(left, right):
    result = []
    while left and right:
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    result.extend(left or right)
    return result

# Example usage:
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = merge_sort(numbers)
print(sorted_numbers)  # Output: [11, 12, 22, 25, 34, 64, 90]

How it Works

  1. The outer loop splits the list into two halves using the mid variable.
  2. Recursively call the merge_sort() function on each half until sublists of length 1 are reached.
  3. Merge the sorted sublists together in sorted order using the merge() function.

Conclusion

In this article, we have explored how to sort lists in Python without using the built-in sort() function. We implemented three different sorting techniques: bubble sort, insertion sort, and merge sort. Each technique has its strengths and weaknesses, but they all demonstrate the fundamental principles of sorting a list in ascending or descending order based on specific criteria.

Whether you’re a seasoned developer or just starting out with Python programming, understanding how to sort lists without relying on the sort() function is an essential skill that can help you write more efficient and effective code.

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp