Examples of O(n^2) Algorithms Explained
Q: Give an example of an algorithm that has a time complexity of O(n^2).
- Big-O Notation
- Junior level question
Explore all the latest Big-O Notation interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Big-O Notation interview for FREE!
One classic example of an algorithm with a time complexity of O(n^2) is the bubble sort algorithm.
In bubble sort, we repeatedly traverse the list to be sorted, comparing adjacent elements. If the elements are in the wrong order, we swap them. This process is repeated until the list is sorted. The outer loop runs n times (where n is the number of elements in the list), and for each iteration of the outer loop, the inner loop also runs n times in the worst-case scenario, resulting in a total time complexity of O(n^2).
Here’s a brief illustration of bubble sort:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)
```
In this example, for a list with n elements, we may need to perform roughly n * (n-1)/2 comparisons in the worst case, leading to the O(n^2) time complexity.
In bubble sort, we repeatedly traverse the list to be sorted, comparing adjacent elements. If the elements are in the wrong order, we swap them. This process is repeated until the list is sorted. The outer loop runs n times (where n is the number of elements in the list), and for each iteration of the outer loop, the inner loop also runs n times in the worst-case scenario, resulting in a total time complexity of O(n^2).
Here’s a brief illustration of bubble sort:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)
```
In this example, for a list with n elements, we may need to perform roughly n * (n-1)/2 comparisons in the worst case, leading to the O(n^2) time complexity.


