冒泡排序優化

一、冒泡排序從頭至尾的掃描,冒泡排序每一次掃描是把前邊未排好序的項中最大的項移到後面 。O :n *  n的2開方。優化

優化1:若前邊的項是有序的,方案1依然會作無謂的掃描。能夠設置一個boolean的標誌位,若上一次進行了交換才進入下一輪掃描。spa

優化2:若排序中有一段是有序的,也不須要重複的掃描。能夠把最後一次交換的位置提出來,下次掃描把這個位置做爲最大的掃描位置。code

//優化2的實現
int bubble(vector<int>* vector1,int lo,int hi){
    int last= 0;
    while(++lo<hi){
        if((*vector1)[lo] < (*vector1)[lo-1]){
            int temp = (*vector1)[lo];
            (*vector1)[lo] = (*vector1)[lo-1];
            (*vector1)[lo-1] = temp;
            last = lo;
        }
    }
    return last;
}

int main() {
    vector<int> vector1(10);
    vector1[0] = 0;
    vector1[1] = 42;
    vector1[2] = 26;
    vector1[3] = 53;
    vector1[4] = 44;
    vector1[5] = 93;
    vector1[6] = 62;
    vector1[7] = 38;
    vector1[8] = 82;
    vector1[9] = 92;

    int m = vector1.size();
    int lo = 0;
    while (0< (m = bubble(&vector1,lo,m))){

    }

    for (int i = 0; i < vector1.size(); ++i) {
        printf("第%d個元素是%d\n",i,vector1[i]);
    }

    return 0;
}
相關文章
相關標籤/搜索