The complexity of an algorithm is defined as the interval of time an algorithm takes to process a provided input. An algorithm can process its provided input in constant, linear, quadratic, exponential, and logarithmic time.
The term Big O refers to the complexity of an algorithm. An algorithm’s complexity increases with the time it takes to run the algorithm.
We define complexity in terms of , , , , and .
- refers to the program executed in constant time.
- refers to the program executed in linear time.
- refers to the program executed in quadratic time
- refers to the program executed in exponential time
- refers to the program executed in logarithmic time
In this shot, we will sort an array of a’s and b’s in linear time.
Let’s consider a one-dimensional array of a’s and b’s, as shown below:
Now we have to sort the given array in ascending order in linear time O(n). After sorting, the array will look like the array given below.
Let’s solve this example using Python.
def sortanb(arr): countofa=0; for i in range(len(arr)): if arr[i]=='a': countofa+=1 countofb=len(arr)-countofa for j in range(len(arr)): if j<=countofb: arr[j]='a' else: arr[j]='b' if __name__ == "__main__": array="ababaab" arr = [char for char in array] sortanb(arr) print("Here is the sorted array :") print(arr)
countofa
from the len(input_array)
, which is the length of the input array.sortanb(input_array)
to sort the char array.RELATED TAGS
View all Courses