Sorting Flashcards
What is the time complexity of sorting an array with Quick Sort?
Average O(n log n), Worst O(n²).
What is the best-case and worst-case time complexity of Merge Sort?
O(n log n) for all cases.
What is the difference between Quick Sort and Merge Sort?
Quick Sort is in-place, but Merge Sort has better worst-case guarantees.
What is the advantage of Heap Sort over Quick Sort?
O(n log n) worst-case complexity; always predictable.
Why is Bubble Sort not used in practice?
O(n²) complexity, too many swaps.
What sorting algorithms have O(n) time complexity?
Counting Sort, Radix Sort, Bucket Sort (non-comparison-based).
What is counting sort, and when is it useful?
Good for small, limited-value integers.
What is the time complexity of inserting an element into a balanced BST?
O(log n) for best, worst, and average cases.
When should you use Quick Sort, Merge Sort, or Heap Sort?
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
What is Topological Sorting, and when is it used?
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 }