Quadratic N^{2} functions needs amount of time that is in quadratic propotional to the number of input elements.

Known algorithms having quadratic time complexity are bubble sort algorithm, selection sort algorithm and insertion sort algorithm.

Any algorithm that involves two loops, one outer loop and one inner loop and both loop iterates N number of times where N is the number of elements in a collection is considered as quadratic function.

Assume that you have two boxes with balls inside it. Each ball has unique color in its own box. It might be possible that same color of ball may exist in another box. You want to create a pair of ball ( one from each box ). How many number of pairs you can create ? Position of the ball matters.

Let's name the boxes as box1 and box2. box1 has 3 balls and box2 has 3 balls. We can represent Boxes as array of Strings.

box1 = {"RED", "GREEN", "YELLOW"};

box2 = {"PINK" , "WHITE" , "BLACK"};

Possible Pairs are :

{"RED", "PINK"}, {"RED", "WHITE"}, {"RED", "BLACK"}

{"GREEN", "PINK"}, {"GREEN", "WHITE"}, {"GREEN", "BLACK"}

{"YELLOW", "PINK"}, {"YELLOW", "WHITE"}, {"YELLOW", "BLACK"}

As you can see total 9 ( 3*3) possibilities are there in which you can select pair of balls, one from each box. For each ball ( total 3 ball ) in first box needs 3 selection from the second box. If you have N1 number of balls in box1 and N2 number of balls in box2, you need N1 * N2 selection.

Programatic implementation of above solution appears as shown below:

**Quadratic Time Complexity Algorithm Example:**

package com.Jwalant.model; public class Example { public static void main(String args[]) { String[] box1 = {"RED", "GREEN", "YELLOW"}; String[] box2 = {"PINK" , "WHITE" , "BLACK"}; for(int i=0; i< box1.length; i++) { for(int j=0; j< box2.length; j++) { System.out.println(" Pair is : ("+box1[i]+","+box2[j]+")"); } } } }

As you can see above that for each iteration of the outer loop, you need to complete inner loop.

In mathematical terms if the number of elements is N, it will get N^{2} selection. Hence it is called quadratic function.

Java is a trademark of Oracle.

Apekshit.com is just for learning and testing. To improve basic understanding we provide some examples. We are constantly reviewing it to avoid errors, but we cannot warrant full correctness of all content.