面試系列3冒泡算法(優(yōu)化)

字號:

冒泡是一個經(jīng)典算法。
    本段代碼增加了一些優(yōu)化:
    增加 b_exchange ,若本輪冒泡沒有交換數(shù)據(jù),則表示排序成功,退出
    增加 n_exchange, n_head ,記錄最近的交換位置,下輪冒泡只要冒到該位置即可
     /********************************************************************
     created: 2006/06/15
     filename: c:/documents and settings/administrator/桌面/tmmp/poposort.c
     file path: c:/documents and settings/administrator/桌面/tmmp
     file base: poposort
     file ext: c
     author: a.tng
     version: 0.0.1
     purpose: 冒泡排序的實現(xiàn)(優(yōu)化)
     增加 b_exchange ,若本輪冒泡沒有交換數(shù)據(jù),則表示排序成功,退出
     增加 n_exchange, n_head ,記錄最近的交換位置,下輪冒泡只要冒到該位置即可
    *********************************************************************/
    #include
    #include
    /*
     * name: poposort
     * params:
     * polist [in/out] 待排序的 int 數(shù)組
     * n [in] int 數(shù)組的長度
     * return:
     * 1-成功 0-失敗
     * notes:
     * 對 polist 進(jìn)行冒泡排序
     *
     * author: a.tng 2006/06/15 9:00
     */
    int poposort(int *polist, int n)
    {
     int i, j;
     int n_exchange;
     if (null == polist)
     return 0;
     n_exchange = 0;
     for (i = 0; i < n - 1; i++)
     {
     /* 最外層循環(huán),冒泡排序需要比較 n-1 輪 */
     int b_exchange;
     int n_head;
     b_exchange = 0;
     n_head = n_exchange;
     for (j = n - 1; j >= n_head + 1; j--)
     {
     /* 第 i 輪比較,把最輕的泡冒置第 i 個位置 */
     if (polist[j] < polist[j - 1])
     {
     int n_tmp_num;
     n_tmp_num = polist[j];
     polist[j] = polist[j - 1];
     polist[j - 1] = n_tmp_num;
     b_exchange = 1;
     n_exchange = j;
     } /* end-if */
     } /* end-for */
     /* 若第 i 輪冒泡結(jié)束,并沒有交換數(shù)據(jù),則表示已經(jīng)排序完成 */
     if (0 == b_exchange)
     return 1;
     } /* end-for */
     return 1;
    }
    /*
     * name: main
     * params:
     * none
     * return:
     * none
     * notes:
     * none
     *
     * author: a.tng 2006/06/15 9:05
     */
    int main()
    {
     // int polist[10] = {45,12,43,11,32,34,91,58,20,82};
     int polist[10] =
     {
     0, 1, 2, 3, 4, 5, 6, 7, 9, 8
     };
     (void) poposort(polist, 10);
     system('pause');
     return 0;
    }