如程序:
#include <iostream> #include <string> using namespace std; int main() { int a[]={15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}; int i,j; int len = sizeof(a)/sizeof(int); cout<<len<<endl; int tmp = 0; int k=0; int flag = 0; for(i =0; i<len; i++) { for(j=0;j<len-i;j++) { if(a[j]>a[j+1]) { tmp = a[j]; a[j]=a[j+1]; a[j+1]=tmp; k++; flag =1; } } if(flag == 0) break; } for(i=0;i<len;i++) { cout<<a[i]<<endl; } cout<<"k="<<k<<endl; }
此时输出:
16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 k=120 ------------------ (program exited with code: 0) Press return to continue
从结果看,排序正确,将数组扩容以后:
#include <iostream> #include <string> using namespace std; int main() { int a[]={16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}; int i,j; int len = sizeof(a)/sizeof(int); cout<<len<<endl; int tmp = 0; int k=0; int flag = 0; for(i =0; i<len; i++) { for(j=0;j<len-i;j++) { if(a[j]>a[j+1]) { tmp = a[j]; a[j]=a[j+1]; a[j+1]=tmp; k++; flag =1; } } if(flag == 0) break; } for(i=0;i<len;i++) { cout<<a[i]<<endl; } cout<<"k="<<k<<endl; }
此时输出结果为:
17 -1217944636 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 k=153 ------------------ (program exited with code: 0) Press return to continue
单击展开
发现新加入的16不见了,而出来一个奇怪的负数,我已经无法理解这种现象了。
时间: 2024-11-08 20:17:47