我已编写此代码进行排序,它运行完全正常。我想知道如何减少时间复杂度。
#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;
}
如果没有其他方法可以更改它,那么我是否必须更改算法?如果是,那么请建议一个算法?
感谢。
答案 0 :(得分:6)
您似乎使用某种选择排序,这已知很慢。 IRL应用程序通常使用quicksort或merge-sort(而不是后者)。
我建议你这样做(假设这是出于教育目的)。
否则,请使用<algorithm>
中定义的std::sort
。
另请注意,您的代码不是标准代码:
cin>>n;
int arr[n];
C ++不支持VLA。你最好使用std::vector
。如果使用C ++,请不要编写C代码。
答案 1 :(得分:3)
您的算法是选择排序,O(n^2)
算法:如果输入大小在n
中线性增长,则运行时间与n
的二次函数成比例。基于对任意输入的排序(即,没有关于输入的先验知识)的最小时间复杂度是O(n log n)
。 STL函数std::sort
提供了这种保证。
#include <algorithm>
#include <vector>
int main()
{
int n;
cin>>n;
std::vector<int> arr;
arr.resize(n);
for(int i=0;i<n; ++i) // ++i rather than i++ is a good habit to get into
{
cin>>arr[i];
}
// O(N log N) complexity
std::sort(arr.begin(), arr.end());
return 0;
}
对于小输入,选择排序(或插入排序)有时可以足够快。您也可以将其编码为C ++ 11中的几行代码(它使用lambda表达式)
#include <algorithm>
#include <iterator>
template<class ForwardIterator>
void selection_sort(ForwardIterator first, ForwardIterator last)
{
std::for_each(first, last, [](ForwardIterator it) { // your outer loop
auto const selection = std::min_element(it, last); // your inner loop
std::iter_swap(selection, it); // your swap code
});
}
// call on your vector
selection_sort(arr.begin(), arr.end());
从这段代码中,选择排序的工作方式也很明显:重复找到数组剩余部分的最小元素,并将其交换到位。它应该等同于您自己的代码,但我希望您同意它更容易理解(一旦您了解STL,就是这样)。
答案 2 :(得分:0)
您正在使用Selection sort对数组进行排序。此算法的运行时间为O(n^2)
。您可以使用Merge sort或Heap Sort对运行时间为O(nlog(n))
的人进行排序
你也可以使用Intro Sort使用一个非常巧妙的技巧将QuickSort's最坏情况下推到O(n log n),同时保持其他良好的性能特征