Answer to Question #185010 in C++ for shahadat

Question #185010

Write a program with analysis to sort in descending manner using 'p' number of values and analyze the complexity.


1
Expert's answer
2021-04-24T15:13:58-0400
#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) 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS