ProgrammingHard
Bubble sort with a swapped flag stops early. On an already sorted array of length n, how many passes run?
- A. n passes, which is O(n^2)
- B. One pass, with no swaps, which makes the best case O(n)
- C. log n passes
- D. Zero passes, since the array is already sorted
Correct answer: B. One pass, with no swaps, which makes the best case O(n)
The first pass makes no swaps, so the flag is clear and the loop ends. The best case is linear.
More C Programming questions
- A recursive binary search on n = 1000 sorted values reaches what maximum recursion depth?
- Merge sort on n = 2^20 elements has what recursion depth?
- An algorithm does O(n) work on each of the n levels of a recursion that removes one element per level. Which total is correct?
- A loop calls strlen(s) on a fixed string of length 10^4 once per character of the same string. How many characters are read in total?
- A function computes the sum of 1 to n by recursion with depth n. For n = 10^6, what is the main risk?
- A program increments a counter inside three nested loops, each running n = 100 times. How many increments occur?