Sobes.tech
Junior

What sorting algorithms do you know?

sobes.tech AI

Answer from AI

The main sorting algorithms I am familiar with:

  1. Bubble Sort. Simple implementation but low efficiency (O(n^2)).
  2. Selection Sort. Also simple, O(n^2), but makes fewer swaps than bubble sort.
  3. Insertion Sort. Efficient for nearly sorted data or small datasets (O(n^2) worst case, O(n) best case).
  4. Merge Sort. Divide-and-conquer algorithm, stable, with O(n log n) average and worst-case complexity. Requires extra O(n) memory.
  5. Quick Sort. Divide-and-conquer, usually the fastest in practice (average O(n log n)), but O(n^2) worst case. Unstable.
  6. Heap Sort. Uses heap data structure. O(n log n), in-place, unstable.

Python supports several built-in sorting algorithms optimized and used by sorted() and list .sort(). Usually, this is Timsort — a hybrid sorting algorithm combining merge sort and insertion sort, very efficient on real-world data.

Here's an example implementation of bubble sort:

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

# Usage example
# my_list = [64, 34, 25, 12, 22, 11, 90]
# bubble_sort(my_list)
# print("Sorted array:", my_list)

Choosing a sorting algorithm depends on requirements: data size, stability, available memory, and data pre-sortedness. In most cases, Python's built-in methods are used due to their optimization.

What sorting algorithms do you know? — Python - sobes.tech