Sorting refers to arranging items in some particular order.
Sorting Methods
Focus Problem – try your best to solve this problem before continuing!
| Resources | |||||
|---|---|---|---|---|---|
| CPH | bubble sort, merge sort, counting sort | ||||
| CSA | selection sort, insertion sort, bubble sort, merge sort | ||||
Library Sorting
Although you usually do not need to know how sorting is implemented, you should know how to use built-in methods.
| Resources | |||||
|---|---|---|---|---|---|
| PY | reference | ||||
Static Arrays
To create a static array in Python, the array module is used. Python does not
have a built in sort method for arrays, but you can use Python's sorted()
function which sorts the array as a list, and returns a list. Then, convert the
list back into an array.
from array import array# "i" denotes integer type of array elementsarr = array("i", [5, 1, 3, 2, 4])print(arr) # Outputs the original arrayprint(sorted(arr)) # Outputs the sorted array, converted to a listarr = array("i", sorted(arr)) # Sorting, then converting back into an arrayprint(arr)
Dynamic Arrays
There's two main ways to sort a list in Python. You can use sorted(arr), which
returns a new list and doesn't modify the old one, or arr.sort(), which sorts
the list in place.
arr = [5, 1, 3, 2, 4]print(sorted(arr)) # Outputs [1, 2, 3, 4, 5]print(arr) # Outputs the original arrayarr.sort()print(arr) # Outputs [1, 2, 3, 4, 5]
For more on sorting in Python, see this link.
(Dynamic) Arrays of Pairs & Tuples
By default, Python tuples sort by first element, then second element, and so on in case of repeated ties.
arr = [(1, 5), (2, 3), (1, 2)]arr = sorted(arr)print(arr) # Outputs [(1, 2), (1, 5), (2, 3)]
Problems
Warning!
Bronze problems are designed so that you shouldn't need a time sort (repeatedly extracting the minimum in time will always suffice).
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CSES | Easy | Show TagsSorting | ||||
| CF | Easy | Show TagsSorting | ||||
| CF | Normal | Show TagsGreedy, Sorting | ||||
| Bronze | Normal | Show TagsSimulation, Sorting | ||||
| Bronze | Normal | Show TagsSorting | ||||
| Bronze | Hard | Show TagsSimulation, Sorting | ||||
| CF | Hard | Show TagsGreedy, Sorting | ||||
Note: There are some more sorting problems in the Intro to Sets module.
Check Your Understanding
What would the array be after 1 pass of bubble sort?
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!