Write a program with analysis to sort in descending manner using 'p' number of values and analyze the complexity.
#include<iostream>
using namespace std;
int main(){
int p,i,arr[50],j,temp;
cout<<"\nNumber of elements to sort:";
cin>>p;
cout<<"\nEnter the "<<p<<" Elements:\n\n";
for(i=0;i<p;i++)
{
cout<<"";
cin>>arr[i];
}
cout<<"\nSorting array ";
for(i=0;i<(p-1);i++)
{
for(j=0;j<(p-1);j++)
{
if(arr[j]<arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"\nSorted elements in descendng order\n:";
for(i=0;i<p;i++)
{
cout<<" ";
cout<<arr[i];
}
}
It's time complexity is (n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1
Sum = n(n-1)/2
i.e O(n2)
Space complexity O(1) as single addition memory requiredspace
required
Best case complexity O(n)
Comments
Leave a comment