a)
Algorithm
Input:
an array of x number of players
Output:
player, friend's index and match value
Explanation.
For every n there is n*n operations O(n^2).
O(n^2) complexity is always demostrated using two loops.
//Let us assume x = 6. But you can change the value of x
int arr[6]= {5,6,7,8,9,10}; //Array containing the players' match value
int arr1[6];
int n;
n = 6; //Putting the number of players to be six
for(int i=0; i<n; i++){ //First loop to perform n operation
int index;
for(int j=1; j<=n; j++){ //Second loop to perform n *n operations
if(arr[i] < arr[j+1]){
index = i;
cout<<index<<endl;
}
}
}
b)
O(n)- This type complexity runs in linear time and n is the number of elements
in the array. This kind of complexity has only one loop.
For this problem, the perfect algorithm can be:
//Let us assume x = 6. But you can change the value of x
int arr[6]= {5,6,7,8,9,10}; //Array containing the players' match value
int arr1[6];
int n;
n = 6; //Putting the number of players to be six
for(int i=0; i<n; i++){ //Loop to perform n operations
int index;
if(arr[i]<arr[i+1]){
index = i;
}
cout<<index;
}
Comments
Leave a comment