双向冒泡排序的基本思想是首先从左向右进行一趟冒泡,将最大数移动到最右边,再从右向左进行一趟冒泡,将最小数移动到最左边,重复这个过程,直到数组有序。
【代码】
#include暑期编程PK赛 得CSDN机械键盘等精美礼品!#include "array.h" #define N 10 void dublebubble(int a[], int n) { int i, j ,temp1,temp2; while (n/2 > 1)//单向冒泡要冒n-1趟,双向只要冒n/2-1趟 { for (i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) { temp1 = a[i]; a[i] = a[i + 1]; a[i + 1] = temp1; } } //一趟从左向右冒泡结束 n--;//最大数已经在最右侧,j从倒数第二个数开始 for (j = n - 1; j >= 0; j--) { if (a[j] < a[j - 1]) { temp2 = a[j]; a[j] = a[j - 1]; a[j - 1] = temp2; } }//一趟从右向左冒泡结束 } } int main() { int a[N]; input(a, N); print(a, N); dublebubble(a, N); print(a, N); return 0; }



