Organizing data allows us to find things faster, but there is no one-size-fits-all approach.
Sorting is one of the most studied problems in computer science. Comparison sorts (like Merge, Quick, and Heap sort) operate by asking "is A bigger than B?". The mathematical limit for this is O(n log n) time.
On the other hand, Non-comparison sorts (like Counting or Radix sort) bypass this limit by exploiting the actual values of the data (like grouping numbers into buckets by their digits), achieving O(n) time, but with strict restrictions on the type of data they can handle.
A classic, stable O(n²) comparison sort is Insertion Sort. While slow for large datasets, it is extremely fast for small or nearly sorted arrays.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# Shift elements greater than key to the right
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
# Place key in its correct position
arr[j + 1] = key
return arr
Merge Sort is O(n log n) time and O(n) space. Quick Sort is typically O(n log n) time and O(log n) space. Heap Sort is O(n log n) time and O(1) space.