# Quadratic time complexity O(n^2)

In algorithmic time, When input data size increases quadratically with algorithmic complexity, quadratical time increases quadratically as well. In other words, for n data points, the quadratic time algorithm can run in as much time as n^2. The nested loop algorithm, which runs from 0 to n-1 in quadratic time, is an example of a quadratic time algorithm. Thus, there are n^2, resulting in a quadratic time complexity.

## Example: Quadratic Time O(n^2)

Lets print all pairs with Quadratic Time.

``````function printAllPairs(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
console.log(arr[i], arr[j]);
}
}
}

const arr = [1,2,3]
printAllPairs(arr); ``````
##### Output
``````1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3 ``````

When i is 1, we iterate j three times.

When i 2, we repeat iteration j 3 times.

In the case of i 3, we repeat iteration j 3 times.

## Example: Quadratic Time O(n^2) using Bubble Sort

When bubble sort is used, adjacent elements are constantly compared and the elements are swapped if the order is incorrect.

``````function bubleSort(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;
}

const arr = [20,40,10,30,50];
console.log(bubleSort(arr));``````
##### Output
``[ 10, 20, 30, 40, 50 ]``
2024 © All rights reserved.