Comparison Based vs Non Comparison Based Sorting in DSA Javascript - Complexity Comparison
Sorting is a common task where we arrange items in order. Different sorting methods take different times depending on how they work.
We want to understand how the time to sort grows as the list gets bigger.
Analyze the time complexity of these two sorting approaches.
// Comparison based sorting example (Bubble Sort)
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// Non-comparison based sorting example (Counting Sort)
function countingSort(arr, max) {
const count = new Array(max + 1).fill(0);
for (let num of arr) count[num]++;
let index = 0;
for (let i = 0; i < count.length; i++) {
while (count[i]-- > 0) {
arr[index++] = i;
}
}
return arr;
}
Bubble Sort compares elements to sort, Counting Sort uses counts without direct comparisons.
Look at the loops and repeated steps in each method.
- Bubble Sort: Two nested loops comparing pairs of elements.
- Counting Sort: One loop to count, one loop to rebuild the array.
- Dominant operation: Bubble Sort's nested comparisons dominate time.
As the list size grows, how does the work increase?
| Input Size (n) | Bubble Sort Ops (approx.) | Counting Sort Ops (approx.) |
|---|---|---|
| 10 | ~100 comparisons | ~10 counts + 10 rebuild |
| 100 | ~10,000 comparisons | ~100 counts + 100 rebuild |
| 1000 | ~1,000,000 comparisons | ~1000 counts + 1000 rebuild |
Bubble Sort grows much faster (square of n), Counting Sort grows roughly linearly with n.
Time Complexity: O(n²) for comparison based (Bubble Sort), O(n + k) for non-comparison based (Counting Sort)
Bubble Sort gets much slower as list grows; Counting Sort stays faster if numbers are in a small range.
[X] Wrong: "All sorting methods take about the same time because they all sort the list."
[OK] Correct: Some methods compare items many times, others use counting tricks that can be much faster for certain data.
Knowing how sorting methods differ helps you choose the right tool and explain your choices clearly in interviews.
What if the input numbers for Counting Sort were very large? How would that affect its time complexity?
Practice
non-comparison based?Solution
Step 1: Understand comparison based sorting
Comparison based sorting algorithms decide order by comparing elements, like Merge Sort, Quick Sort, and Heap Sort.Step 2: Identify non-comparison based sorting
Counting Sort uses counting of element frequencies instead of comparisons, so it is non-comparison based.Final Answer:
Counting Sort -> Option DQuick Check:
Non-comparison based = Counting Sort [OK]
- Confusing Quick Sort as non-comparison
- Thinking Merge Sort is non-comparison
- Assuming Heap Sort is non-comparison
countingSort(arr) in JavaScript?Solution
Step 1: Recall JavaScript function call syntax
Functions are called with parentheses enclosing arguments, likefunc(args).Step 2: Match syntax with options
OnlycountingSort(arr);uses correct parentheses syntax for function call.Final Answer:
countingSort(arr); -> Option AQuick Check:
Function call syntax = countingSort(arr); [OK]
- Using square brackets [] instead of parentheses
- Missing parentheses around arguments
- Using curly braces {} incorrectly
function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max + 1).fill(0);
arr.forEach(num => count[num]++);
let sorted = [];
count.forEach((c, num) => {
for (let i = 0; i < c; i++) sorted.push(num);
});
return sorted;
}
const arr = [3, 1, 4, 1, 5];
console.log(countingSort(arr));Solution
Step 1: Count frequencies of each number
Input array is [3,1,4,1,5]. Counting frequencies: 1 appears 2 times, 3 once, 4 once, 5 once.Step 2: Build sorted array from counts
Using counts, output array is [1,1,3,4,5] in ascending order.Final Answer:
[1, 1, 3, 4, 5] -> Option AQuick Check:
Counting Sort output = sorted ascending array [OK]
- Confusing input and output arrays
- Assuming original order is preserved
- Thinking output is reversed
function countingSort(arr) {
const max = Math.max(...arr);
const count = new Array(max).fill(0);
arr.forEach(num => count[num]++);
let sorted = [];
count.forEach((c, num) => {
for (let i = 0; i < c; i++) sorted.push(num);
});
return sorted;
}Solution
Step 1: Check count array size
Count array size ismax, but indices go from 0 to max, so size must be max + 1.Step 2: Identify impact of wrong size
Without max + 1 size, count[max] index is undefined, causing errors or missing counts.Final Answer:
Array count size should be max + 1 -> Option BQuick Check:
Count array size = max + 1 [OK]
- Using max instead of max + 1 for array size
- Confusing max with min
- Ignoring array initialization
Solution
Step 1: Analyze input constraints
Array elements range from 0 to 1000, so range size k = 1001, which is small and fixed.Step 2: Choose sorting algorithm based on range
Counting Sort runs in O(n + k), which is efficient for small k, better than O(n log n) comparison sorts.Step 3: Confirm Counting Sort suitability
Counting Sort is non-comparison based and ideal for small integer ranges.Final Answer:
Counting Sort, because it sorts in O(n + k) where k is range size -> Option CQuick Check:
Small range + Counting Sort = efficient sorting [OK]
- Choosing Quick Sort ignoring range size
- Assuming Merge Sort is always best
- Not considering non-comparison sorts
Ready to prove it?
Pass the test and this pattern moves unknown
