面試系列3--冒泡算法(優化)
冒泡是一個經典算法。
本段代碼增加了一些優化:
增加 b_exchange ,若本輪冒泡沒有交換數據,則表示排序成功,退出
增加 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:??? 冒泡排序的實現(優化)
??????????????? 增加 b_exchange ,若本輪冒泡沒有交換數據,則表示排序成功,退出
??????????????? 增加 n_exchange, n_head ,記錄最近的交換位置,下輪冒泡只要冒到該位置即可
*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
/*
?*? name: poposort
?*? params:
?*??? polist??????????? [in/out]??????? 待排序的 int 數組
?*??? n???????????????? [in]??????????? int 數組的長度
?*? return:
?*??? 1-成功 0-失敗
?*? notes:
?*??? 對 polist 進行冒泡排序
?*?
?*? 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++)
??? {
??????? /* 最外層循環,冒泡排序需要比較 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 輪冒泡結束,并沒有交換數據,則表示已經排序完成 */
??????? 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;
}
?
posted on 2007-09-05 01:16 旅途 閱讀(154) 評論(0) 編輯 收藏 引用 所屬分類: C/C++