Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrease time complexity of sorting?

I have written this code for sorting, it runs completely fine. I wanted to knwo how I can reduce its time complexity.

#include <iostream>

using namespace std;

void sort(int a[], int n)
{
    int min, temp;
    for(int i=0;i<n-1;i++)
    {
        min=i;
        for(int j=i+1;j<n;j++)
        {
            if(a[min]>a[j])
            {
                min=j;
            }
        }
        temp=a[i];
        a[i]=a[min];
        a[min]=temp;
    }
    for(int i=0;i<n;i++)
    {
        cout<<a[i]<<endl;
    }
}
int main()
    {
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    sort(arr,n);
    return 0;
}

If there is no other way to change it then do I have to change the algorithm? If so then please suggest an algorithm?

Thanks.

like image 862
praxmon Avatar asked Sep 22 '26 23:09

praxmon


1 Answers

It seems like your using some sort of selection sort, which is known to be slow. IRL applications usually use quicksort or merge-sort (not so much the latter).

I suggest you do the same (assuming this is for educational purposes).

Otherwise, use std::sort defined in <algorithm>.

Also, note that your code is not standard:

cin>>n;
int arr[n];

VLA's are not supported in C++. You're better of using a std::vector instead. If you use C++, don't write C code.

like image 59
Luchian Grigore Avatar answered Sep 25 '26 12:09

Luchian Grigore