Sorting Arrays in Python: Techniques and Methods
Explore how to sort arrays in Python with various techniques. Although the array module lacks a built-in sorting function, you can sort arrays using sorting algorithms, the sort() method from lists, or the built-in sorted() function. This guide provides practical methods and examples for arranging array elements in order.
Python - Sort Arrays
Python's array module defines the array class, similar to arrays in Java or C/C++. Unlike built-in Python sequences, arrays are homogeneous collections of either strings, integers, or floats.
The array class doesn't have a built-in function to sort its elements, but sorting can be achieved using one of the following approaches:
- Using a sorting algorithm
- Using the
sort()method from List - Using the built-in
sorted()function
Python Array Sorting
Sort Arrays Using a Sorting Algorithm
Implementing the classical bubble sort algorithm to sort an array involves using two nested loops to swap elements into a sorted order.
Example
import array as arr
a = arr.array('i', [10, 5, 15, 4, 6, 20, 9])
for i in range(0, len(a)):
for j in range(i + 1, len(a)):
if a[i] > a[j]:
temp = a[i]
a[i] = a[j]
a[j] = temp
print(a)
Output
array('i', [4, 5, 6, 9, 10, 15, 20])
Sort Arrays Using sort() Method of List
Even though the array module doesn't have a sort() method, Python's built-in List class does. First, declare an array and obtain a list object from it using the tolist() method. Then, use the sort() method to sort the list and create another array using the sorted list.
Example
import array as arr
# creating array
orgnlArray = arr.array('i', [10, 5, 15, 4, 6, 20, 9])
print("Original array:", orgnlArray)
# converting to list
sortedList = orgnlArray.tolist()
# sorting the list
sortedList.sort()
# creating array from sorted list
sortedArray = arr.array('i', sortedList)
print("Array after sorting:", sortedArray)
Output
Original array: array('i', [10, 5, 15, 4, 6, 20, 9])
Array after sorting: array('i', [4, 5, 6, 9, 10, 15, 20])
Sort Arrays Using sorted() Method
The sorted() function is a built-in function that can sort an array. The function returns a new list containing all items from the iterable in ascending order. Set the reverse parameter to True to get a descending order of items.
Example
import array as arr
a = arr.array('i', [10, 5, 15, 4, 6, 20, 9])
sorted_array = arr.array('i', sorted(a))
print(sorted_array)
Output
array('i', [4, 5, 6, 9, 10, 15, 20])