Python - Sort Arrays

Hello there, aspiring Python programmers! Today, we're going to dive into the wonderful world of sorting arrays in Python. Don't worry if you're new to programming – I'll guide you through each step with plenty of examples and explanations. By the end of this tutorial, you'll be sorting arrays like a pro!

Python - Sort Arrays

What is an Array in Python?

Before we jump into sorting, let's quickly talk about what an array is in Python. In Python, we typically use lists to represent arrays. A list is a collection of items that can be of different types. For example:

fruits = ["apple", "banana", "cherry", "date"]
numbers = [42, 8, 15, 16, 23]

Sort Arrays Using a Sorting Algorithm

Let's start with a basic sorting algorithm called Bubble Sort. It's not the most efficient, but it's easy to understand for beginners.

Bubble Sort

Here's a simple implementation of Bubble Sort:

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

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

Let's break this down:

  1. We define a function called bubble_sort that takes an array (list) as input.
  2. We get the length of the array and store it in n.
  3. We use two nested loops to compare adjacent elements.
  4. If an element is greater than the next one, we swap them.
  5. We repeat this process until the entire array is sorted.

When you run this code, you'll see:

Sorted array: [11, 12, 22, 25, 34, 64, 90]

Fun fact: Bubble Sort is called so because smaller elements "bubble" to the top of the list with each iteration!

Sort Arrays Using sort() Method of List

Python lists have a built-in sort() method that makes sorting much easier. Let's see how it works:

# Sorting numbers
numbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort()
print("Sorted numbers:", numbers)

# Sorting strings
fruits = ["banana", "cherry", "apple", "date"]
fruits.sort()
print("Sorted fruits:", fruits)

Output:

Sorted numbers: [11, 12, 22, 25, 34, 64, 90]
Sorted fruits: ['apple', 'banana', 'cherry', 'date']

The sort() method modifies the original list. It's like tidying up your room – everything ends up in order, but it's still your room!

Sorting in Reverse Order

You can also sort in descending order by adding the reverse=True parameter:

numbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort(reverse=True)
print("Sorted numbers (descending):", numbers)

Output:

Sorted numbers (descending): [90, 64, 34, 25, 22, 12, 11]

Sort Arrays Using sorted() Function

The sorted() function is another powerful tool in Python for sorting. Unlike sort(), it doesn't modify the original list but returns a new sorted list.

# Sorting numbers
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = sorted(numbers)
print("Original numbers:", numbers)
print("Sorted numbers:", sorted_numbers)

# Sorting strings
fruits = ["banana", "cherry", "apple", "date"]
sorted_fruits = sorted(fruits)
print("Original fruits:", fruits)
print("Sorted fruits:", sorted_fruits)

Output:

Original numbers: [64, 34, 25, 12, 22, 11, 90]
Sorted numbers: [11, 12, 22, 25, 34, 64, 90]
Original fruits: ['banana', 'cherry', 'apple', 'date']
Sorted fruits: ['apple', 'banana', 'cherry', 'date']

Think of sorted() as making a copy of your list and sorting that copy, leaving the original untouched. It's like taking a photo of your messy room, then arranging everything neatly in the photo while your actual room stays the same!

Sorting with Custom Keys

One of the coolest features of sorted() is the ability to use custom sorting keys. Let's say we want to sort a list of words by their length:

words = ["python", "is", "awesome", "and", "fun"]
sorted_words = sorted(words, key=len)
print("Sorted by length:", sorted_words)

Output:

Sorted by length: ['is', 'and', 'fun', 'python', 'awesome']

Here, we used len as the key function. Python applies this function to each item and sorts based on the result.

Comparison of Sorting Methods

Let's summarize the sorting methods we've learned in a handy table:

Method Modifies Original Returns New List Can Use Custom Key
Bubble Sort Yes No No
list.sort() Yes No Yes
sorted() No Yes Yes

Conclusion

Congratulations! You've just learned several ways to sort arrays in Python. From implementing your own sorting algorithm to using Python's built-in methods, you now have the tools to keep your data organized.

Remember, sorting is like arranging books on a shelf – there are many ways to do it, and the best method depends on what you're trying to achieve. Practice with different types of data and sorting methods to become a Python sorting master!

Happy coding, and may your arrays always be perfectly sorted! ??

Credits: Image by storyset