冒泡排序簡單改進

int main(void)
{
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    bool temp = true;

    for (int i = 0; i < 9; i++)
    {
        temp = false;//首先將其置爲false
        for (int j = 0; j < 9 - i; j++)
        {
            if (a[j] > a[j + 1])
            {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
                temp = true;//若發生交換,則爲true
            }
        }
        if (!temp)//若上一輪比較沒有發生交換,則爲數組有序,則退出循環
            break;
    }
    for (int i = 0; i < 10; i++)
        printf("%d  ",a[i]);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章