Sicily-选择排序比较次数

选择排序的比较次数为n(n-1)/2,但是这里还是通过老老实实的比较来进行次数累加,为的就是更明白选择排序的原理。

选择排序的原理:在未排序的数中选出最小的数同未排序数的首位比较,如果比它小,互换位置。

 

#include<cstdio> 
#include<iostream> 
using namespace std;
int main() {
    int N = 0;
    while(scanf("%d", &N) != EOF) {
        int a[1000];
        int com = 0;
        for (int i = 0; i < N; i++) {
            cin >> a[i];
        }
        int begin = 0;
        for (int j = 0; j < N; j++) {
            int small = a[begin];
            int pos = 0;
            for (int i = begin+1; i < N; i++) {
                if (a[i] < small) {
                    small = a[i];
                    pos = i;
                }
                com++;
            }
            //cout << small << " " ;
            if (small < a[begin]) {
                int temp = 0;
                temp = a[begin];
                a[begin] = a[pos];
                a[pos] = temp;
            }
            begin++;
        }
        /*for (int i = 0; i<N;i++) {
            cout << a[i] << " " ;
        }*/
        cout << com << endl;
        //int k = 0;
        //k = N*(N-1)/2;
        //cout << k << endl;
    }
    
    return 0;
}                     

 

posted @ 2017-01-19 16:31  SYSU_Bango  阅读(610)  评论(0)    收藏  举报