5 Best Ways to Sort an Array in Python

πŸ’‘ Problem Formulation: Sorting is a common necessity in programming. Take, for example, an array representing student scores: [68, 85, 90, 55, 60]. We might want to sort these to facilitate other operations, such as ranking or simply improving readability. The desired output for sorting in ascending order would be [55, 60, 68, 85, 90], whereas sorting in descending order would yield [90, 85, 68, 60, 55]. This article shall explore several methods for sorting arrays in Python, providing examples and discussions of each.

Method 1: Using the Sorted Function

The sorted() function is a built-in Python function that returns a new sorted list from the items in an iterable. This method is versatile, as it allows us to specify the direction of the sort (ascending or descending) and the key to sort by, if sorting complex objects.

Here’s an example:

array = [68, 85, 90, 55, 60]
sorted_array = sorted(array)
print(sorted_array)

Output:

[55, 60, 68, 85, 90]

This code snippet demonstrates the use of the sorted() function to sort an array of integers in ascending order, resulting in a new sorted list that is printed to the console.

Method 2: Using the List’s sort Method

The list.sort() method sorts the list in place, meaning the original list is modified. This method does not return a new list, making it more memory efficient. It also shares the flexibility of the sorted() function in terms of specifying sort order and key function.

Here’s an example:

array = [68, 85, 90, 55, 60]
array.sort()
print(array)

Output:

[55, 60, 68, 85, 90]

In this snippet, the sort() method is used to rearrange the elements of array in ascending order. The same array is then printed to show the sorted order.

Method 3: Using the Bubble Sort Algorithm

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Though it is easy to understand and implement, it is not suitable for large datasets due to its time complexity of O(n^2).

Here’s an example:

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]

array = [68, 85, 90, 55, 60]
bubble_sort(array)
print(array)

Output:

[55, 60, 68, 85, 90]

This code defines a function bubble_sort() that implements the bubble sort algorithm. The function is then used to sort an array in ascending order.

Method 4: Using the Quicksort Algorithm

Quicksort is a divide-and-conquer algorithm that selects a ‘pivot’ element from the array and partitions the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. This method is efficient for large datasets, with an average time complexity of O(n log n).

Here’s an example:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr.pop()
        less = [x for x in arr if x  pivot]
        return quicksort(less) + [pivot] + quicksort(greater)

array = [68, 85, 90, 55, 60]
sorted_array = quicksort(array)
print(sorted_array)

Output:

[55, 60, 68, 85, 90]

The provided example illustrates the Quicksort algorithm in Python. It defines a recursive function named quicksort() that operates by selecting a pivot and partitioning the array into sub-arrays, which are then sorted separately.

Bonus One-Liner Method 5: Using List Comprehensions and the Walrus Operator

In Python 3.8 and above, the walrus operator (:=) can be used to condense code and facilitate assignments within an expression, such as a list comprehension. This experimental approach can result in a compact, though less readable, one-liner sorting method.

Here’s an example:

array = [68, 85, 90, 55, 60]
print(sorted_array := sorted(array))

Output:

[55, 60, 68, 85, 90]

This nifty one-liner uses the walrus operator to assign the sorted array to the variable sorted_array while also printing it.

Summary/Discussion

  • Method 1: Using the Sorted Function. It’s universal and convenient as it returns a new sorted list and doesn’t affect the original array. However, it might not be the most memory-efficient for very large datasets.
  • Method 2: Using the List’s sort Method. It sorts the list in place which can be more efficient with memory but has the side effect of changing the original list.
  • Method 3: Using the Bubble Sort Algorithm. This classic algorithm is straightforward but inefficient for large lists due to its higher computational complexity.
  • Method 4: Using the Quicksort Algorithm. QuickSort is a fast and scalable algorithm that is well-suited for large datasets, though its performance degrades if not implemented carefully.
  • Bonus Method 5: Using List Comprehensions and the Walrus Operator. It demonstrates modern Python syntax to achieve a task in a condensed fashion but may sacrifice code readability and maintainability.