Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
Bubble sort is written with a flag that stops it when a full pass makes no swap. What is its time complexity on an array that is already sorted?
- A. O(1)
- B. O(n)
- C. O(n²)
- D. O(n log n)
Correct answer: B. O(n)
The first pass makes n − 1 comparisons and no swap, so the algorithm stops: O(n). Without the flag it would still run all passes and take O(n²).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Kadane's algorithm is run on [3, −4, 5, −1, 2, −6, 4]. What maximum contiguous subarray sum does it return?
- What is the auxiliary space used by the standard top-down merge sort on an array of n elements?
- In a singly linked list you are given only a pointer to a node X (not the last node) and no head pointer. How can X be deleted, and in…
- Which of these is NOT a typical application of a stack?
- A sorted array of n integers is given. Using the two-pointer technique, what are the time and extra space needed to decide whether some…
- The numbers 1, 2, 3, 4, 5 are pushed onto a stack in that order, and pops may happen at any time in between. Which output sequence is…