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!

How to Sort a List in Python Without the Sort Function

Learn how to sort lists in Python without using the built-in sort function, exploring alternative methods and best practices for efficient sorting.| …


Updated July 25, 2023

|Learn how to sort lists in Python without using the built-in sort function, exploring alternative methods and best practices for efficient sorting.|

Sorting a list is one of the most fundamental operations in programming, and Python offers several ways to achieve this. While the sort() function is often the first choice, there are many scenarios where you might need to implement custom sorting logic or optimize your code for specific use cases.

In this article, we’ll delve into various techniques to sort a list without using the sort() function. We’ll explore methods that take advantage of Python’s built-in functions and data structures, providing step-by-step explanations and code snippets along the way.

Definition of Sorting

Sorting is the process of arranging elements in a list or other iterable according to specific criteria, such as alphabetical order or numerical value. There are many types of sorting algorithms, including bubble sort, selection sort, merge sort, quicksort, and heapsort, each with its own strengths and weaknesses.

Types of Sorting:

  1. Ascending Order: Smallest values come first.
  2. Descending Order: Largest values come first.
  3. Alphabetical Order: Strings are sorted alphabetically.
  4. Numerical Order: Integers or floats are sorted numerically.

Method 1: Using the sorted() Function

While not exactly without the sort() function, using the sorted() function can achieve similar results and is often overlooked as a viable option. The sorted() function returns a new list that contains all items from the original list in ascending order.

def sorted_list(lst):
    return sorted(lst)

numbers = [4, 2, 9, 6, 1]
print(sorted_list(numbers))  # Output: [1, 2, 4, 6, 9]

Step-by-Step Explanation:

  • The sorted() function takes an iterable (in this case, a list) as input.
  • It returns a new list that contains all items from the original list in ascending order.
  • By using the sorted() function, you can easily sort lists without implementing custom sorting logic.

Method 2: Implementing Merge Sort

Merge sort is a popular sorting algorithm with a time complexity of O(n log n). It works by recursively splitting the input list into smaller chunks, sorting each chunk individually, and then merging the sorted chunks back together.

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):
    merged = []
    i = j = 0

    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1

    merged.extend(left[i:])
    merged.extend(right[j:])
    return merged

numbers = [4, 2, 9, 6, 1]
print(merge_sort(numbers))  # Output: [1, 2, 4, 6, 9]

Step-by-Step Explanation:

  • The merge_sort() function takes a list as input.
  • If the length of the list is less than or equal to 1 (i.e., it contains only one element), return the list itself (since it’s already sorted).
  • Split the list into two halves, and recursively sort each half using the merge_sort() function.
  • Merge the sorted halves back together using the merge() function.

Method 3: Implementing Quick Sort

Quicksort is another popular sorting algorithm with a time complexity of O(n log n) on average. It works by selecting a pivot element, partitioning the input list around it, and then recursively sorting each partition.

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

numbers = [4, 2, 9, 6, 1]
print(quick_sort(numbers))  # Output: [1, 2, 4, 6, 9]

Step-by-Step Explanation:

  • The quick_sort() function takes a list as input.
  • If the length of the list is less than or equal to 1 (i.e., it contains only one element), return the list itself (since it’s already sorted).
  • Select a pivot element from the middle of the list, and partition the rest of the list into three parts: elements less than the pivot, elements equal to the pivot, and elements greater than the pivot.
  • Recursively sort each partition using the quick_sort() function.

In conclusion, sorting a list without using the sort() function can be achieved through various techniques. The sorted() function provides an easy-to-use alternative for simple cases. Merge sort and quick sort are more complex algorithms with better performance characteristics but require more implementation effort. By understanding these methods and their trade-offs, you can choose the best approach for your specific use case.

I hope this article has provided a thorough explanation of how to sort lists in Python without using the sort() function.

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

Intuit Mailchimp