Sorting¶
Bubble Sort¶
Bubble sort is a simple comparison-based sorting algorithm. It works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The process is repeated until the list is sorted.
- Time complexity: O(n^2)
- Space complexity: O(1)
Insertion Sort¶
Insertion sort is a simple comparison-based sorting algorithm. It builds the sorted array one item at a time by repeatedly taking the next unsorted item and inserting it into the correct position in the already sorted portion of the array.
- Time complexity: O(n^2)
- Space complexity: O(1)
Selection Sort¶
Selection sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and swapping it with the first unsorted element until the entire list is sorted.
- Time complexity: O(n^2)
- Space complexity: O(1)
Merge Sort¶
Merge sort is a divide-and-conquer algorithm that works by recursively dividing the list into smaller sublists until each sublist contains a single element. Then, it merges those sublists back together in a sorted order.
- Time complexity: O(n log n)
- Space complexity: O(n)
Quick Sort¶
Quick sort is a divide-and-conquer algorithm that works by selecting a 'pivot' element from the array and partitioning 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.
- Time complexity: O(n log n) on average, O(n^2) in the worst case
- Space complexity: O(log n) on average, O(n) in the worst case
Counting Sort¶
Counting sort is a non-comparison-based sorting algorithm that works by counting the number of occurrences of each unique element in the input array. It then uses this count to determine the position of each element in the output array.
- Time complexity: O(n + k), where n is the number of elements in the input array and k is the range of the input values
-
Space complexity: O(n + k)
-
k: the range of the input values (the difference between the maximum and minimum values in the input array)
Python Sort methods¶
Tim sort is the built-in sorting algorithm in Python, which is a hybrid sorting algorithm derived from merge sort and insertion sort. It is designed to perform well on many kinds of real-world data.
- Time complexity: O(n log n) on average, O(n) in the best case (when the input is already sorted)
- Space complexity: O(n)
Methods:
- sorted: returns a new sorted list from the items in an iterable.
- list.sort: sorts the list in place and returns None.
Sorting a list of tuples