QA
Beginner LevelData Structures & Algorithms

Explain Bubble Sort, Selection Sort, and Insertion Sort with their complexities.

ā“ Interview Prompt: Compare the three basic O(N²) sorting algorithms: Bubble Sort, Selection Sort, and Insertion Sort — best/average/worst cases and when each is preferred.

Bubble Sort

Repeatedly swaps adjacent elements if out of order. Optimised with early exit if no swaps occurred in a pass.

•
Best: $O(N)$ (already sorted, with flag), Worst/Average: $O(N^2)$.

Selection Sort

Finds the minimum in the unsorted portion and swaps it to the correct position. Always $O(N^2)$ regardless of input.

•
Pro: Minimises number of swaps ($O(N)$ swaps vs $O(N^2)$ for Bubble).

Insertion Sort

Builds a sorted sub-array from left to right, inserting each element into its correct position.

•
Best: $O(N)$ (nearly sorted input), Worst/Average: $O(N^2)$.
•
When to use: Excellent for small arrays ($N < 20$) or nearly sorted data — used as the base case inside Timsort.

Code Implementation Example

typescript
// Insertion Sort — O(N²) worst, O(N) best
function insertionSort(arr: number[]): number[] {
  for (let i = 1; i < arr.length; i++) {
    const key = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j]; // shift right
      j--;
    }
    arr[j + 1] = key;
  }
  return arr;
}

console.log(insertionSort([5, 2, 4, 6, 1, 3])); // [1,2,3,4,5,6]
šŸ’”Insertion Sort — optimal for small or nearly-sorted arrays.
šŸŽÆ Interview Key Takeaway

Insertion Sort is the best O(N²) algorithm for nearly-sorted data. All three have O(1) space. Prefer Merge/Quick sort for large N.

#DSA#Sorting#Bubble Sort#Insertion Sort#Beginner
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?