Sorting Flashcards

1
Q

What is the time complexity of sorting an array with Quick Sort?

A

Average O(n log n), Worst O(n²).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

What is the best-case and worst-case time complexity of Merge Sort?

A

O(n log n) for all cases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between Quick Sort and Merge Sort?

A

Quick Sort is in-place, but Merge Sort has better worst-case guarantees.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the advantage of Heap Sort over Quick Sort?

A

O(n log n) worst-case complexity; always predictable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why is Bubble Sort not used in practice?

A

O(n²) complexity, too many swaps.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What sorting algorithms have O(n) time complexity?

A

Counting Sort, Radix Sort, Bucket Sort (non-comparison-based).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is counting sort, and when is it useful?

A

Good for small, limited-value integers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the time complexity of inserting an element into a balanced BST?

A

O(log n) for best, worst, and average cases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When should you use Quick Sort, Merge Sort, or Heap Sort?

A

Quick Sort Best for random data, in-place, very fast O(n log n) avg, O(n²) worst

Merge Sort Best for linked lists or stable sorting O(n log n) worst

Heap Sort Best for priority-based sorting O(n log n) always

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is Topological Sorting, and when is it used?

A

Used in dependency resolution problems (e.g., course scheduling).

Works only on DAGs (Directed Acyclic Graphs).

Can be implemented via DFS (Stack) or Kahn’s Algorithm (BFS In-Degree Count).

function topologicalSort(graph) {
let inDegree = Object.fromEntries(Object.keys(graph).map(node => [node, 0]));

// Compute in-degree for each node
for (let node in graph) {
    for (let neighbor of graph[node]) {
        inDegree[neighbor]++;
    }
}

let queue = Object.keys(inDegree).filter(node => inDegree[node] === 0);
let topoOrder = [];

while (queue.length > 0) {
    let node = queue.shift();
    topoOrder.push(node);
    for (let neighbor of graph[node] || []) {
        inDegree[neighbor]--;
        if (inDegree[neighbor] === 0) {
            queue.push(neighbor);
        }
    }
}

return topoOrder.length === Object.keys(graph).length ? topoOrder : []; // Return empty if cycle detected }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly