PrevNext

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 elements
arr = array("i", [5, 1, 3, 2, 4])
print(arr) # Outputs the original array
print(sorted(arr)) # Outputs the sorted array, converted to a list
arr = array("i", sorted(arr)) # Sorting, then converting back into an array
print(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 array
arr.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 O(NlogN)\mathcal{O}(N\log N) time sort (repeatedly extracting the minimum in O(N2)\mathcal{O}(N^2) time will always suffice).

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsSorting
CFEasy
Show TagsSorting
CFNormal
Show TagsGreedy, Sorting
BronzeNormal
Show TagsSimulation, Sorting
BronzeNormal
Show TagsSorting
BronzeHard
Show TagsSimulation, Sorting
CFHard
Show TagsGreedy, Sorting

Note: There are some more sorting problems in the Intro to Sets module.

Check Your Understanding

What would the array [7,2,6,3,1][7, 2, 6, 3, 1] be after 1 pass of bubble sort?

Question 1 of 4

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!

PrevNext