What is the time complexity of the bubble sort algorithm?
Practice Questions
Q1
What is the time complexity of the bubble sort algorithm?
O(n)
O(n log n)
O(n^2)
O(log n)
Questions & Step-by-Step Solutions
What is the time complexity of the bubble sort algorithm?
Step 1: Understand what time complexity means. It measures how the time to complete an algorithm grows as the size of the input (n) increases.
Step 2: Know that bubble sort is a sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Step 3: Realize that bubble sort uses two loops: an outer loop that goes through the entire list and an inner loop that compares adjacent elements.
Step 4: The outer loop runs n times (where n is the number of elements in the list). For each iteration of the outer loop, the inner loop can also run up to n times in the worst case.
Step 5: Since the inner loop runs n times for each of the n iterations of the outer loop, the total number of comparisons is n * n, which is n^2.
Step 6: Therefore, the worst-case time complexity of bubble sort is O(n^2).