冒泡排序
若用冒泡排序法对序列18,14,6,27,8,12,16,52,10,26,47,29,41,24从小到大进行排序,其要进行( )次比较。A)33 B)45 C)70 D)91
[此贴子已经被作者于2016-7-1 14:02编辑过]
#include<stdio.h> void _Swap(int &a, int &b) { int c = a; a = b; b = c; } void _Printf(int a[], int n) { for (int i=0; i<n; i++) printf("%d ", a[i]); putchar('\n'); } int _Sort1(int a[], int n) { int count = 0; for (int i=0; i<n; i++) { for (int j=1; j<n-i; j++) { count++; if (a[j-1] > a[j]) _Swap(a[j-1], a[j]); } } return count; } int _Sort2(int a[], int n) { int count = 0; int k = n; bool flag = true; while (flag) { flag = false; for (int j=1; j<k; j++) { count++; if (a[j-1] > a[j]) { _Swap(a[j-1], a[j]); flag = true; } } k--; } return count; } main() { int n = 14; int a1[] = {18,14,6,27,8,12,16,52,10,26,47,29,41,24}; int a2[] = {18,14,6,27,8,12,16,52,10,26,47,29,41,24}; _Printf(a1, n); int count = _Sort1(a1, n); _Printf(a1, n); printf("方法一比较次数:%d\n", count); count = _Sort2(a2, n); _Printf(a2, n); printf("方法二比较次数:%d\n", count); }