我有一个函数,它可以接受两个元素并以升序返回它们:
void Sort2(int &a, int &b) {
if (a < b) return;
int t = a;
a = b;
b = t;
}
如果不允许我使用额外的条件运算符,使用此函数对具有 N 个条目的数组进行排序的最快方法是什么? 这意味着我的整个程序应该是这样的:
int main(){
int a[N];
// fill a array
const int NS = ...; // number of comparison, depending on N.
const int c[NS] = { {0,1}, {0,2}, ... }; // consequence of indices pairs generated depending on N.
for( int i = 0; i < NS; i++ ) {
Sort2(a[c[i][0]], a[c[i][1]]);
}
// sort is finished
return 1;
}
大多数快速排序算法使用条件来决定要做什么。当然有冒泡排序,但需要 M = N(N-1)/2 次比较。这不是最优的,例如,当 N = 4 时,它需要 M = 6 比较,同时 4 个条目可以用 5 排序:
Sort2(a[0],a[1]);
Sort2(a[2],a[3]);
Sort2(a[1],a[3]);
Sort2(a[0],a[2]);
Sort2(a[1],a[2]);