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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With