What is Big O Notation?
Big O Notation used in computer science to measure the performance or complexity of an algorithm.
Below are the some examples for Big O Notation
O(1) - Order of 1
Describes an algorithm that will always execute in the same time or space irrespective of the input size. Example. Lets assume dataset length is 5. If dataset length is 5 or whatever below code will execute only one time i.e dataset[0].
function NullCheckForFirstElement(List dataset)
{
return dataset[0] == null;
}
O(N)
- Order of N
Describes an algorithm which always execute
all the elements in the dataset. If dataset length is 5 then order of execution also 5. It matches direct proportion based on the dataset length. For example
function ContainsValue(List<string> elements, string value)
{
foreach (var element in elements)
{
if (element == value) return true;
}
return false;
}
O(N2) - Order of N2
Describes an algorithm which always perform square of the N execution. Look at the below example. If elements size is 5 then for loop executes 5x5 = 25 times which means 52
function checkDuplicates(List<string> elements)
{
for (var i = 0; i < elements.Count; i++)
{
for (var j = 0; j < elements.Count; j++)
{
if (i == j) continue;
if (elements[i] == elements[j]) return true;
}
}
return false;
}
O(2N)
O(2N)
Describes an algorithm which executes total number of elements two times. For example
function showData(int arr[], int size)
{
for(int i = 0; i < size; i++)
System.out.print(arr[i]);
for(int i = 0; i < size; i++)
System.out.print(arr[i]);
}
This one is called O(2n) which we say O(N).