//Bubble Sort
#include <stdio.h>
int psort(int *, int);
int main(void)
{
int arr[10] = {1,23,2,56,7,9,12,13,8,17 };
int ans[10] = {0};
int len = sizeof(ans)/sizeof(ans[0]);
printf("len =%d\n",len);
for(int i=0;i<len;i++){
ans[i]=arr[i];
printf("数组值依次为:%d\n",ans[i]);
}
psort(ans,len);
for(int i=0;i<len;i++){
printf("排序之后,数组值依次为:%d\n",ans[i]);
}
return 0;
}
int psort(int *pchange ,int length)
{
int flag;
for ( int i=1; i<length;i++) {
flag = 1;
for (int j=0; j< length-i;j++){
if ( pchange[j] > pchange[j+1]) {
int tmp= pchange[j];
pchange[j] = pchange[j+1];
pchange[j+1] = tmp;
flag = 0;
}
}
if (flag){
break;
}
}
return flag;
}
console运行结果如下:
双重for循环,所以时间复杂度是:O(n²), 变量的内存分配都是在定义的时候,也就有限数量,所以空间复杂度是O(1)。
这个代码容易埋坑的地方是这个双重for循环, 若为以下写法,会出现pchange[length],导致数组越界。
for ( int i=0; i<length-1;i++) {
flag = 1;
for (int j=0; j< length-i;j++){
if ( pchange[j] > pchange[j+1]) {
int tmp= pchange[j];
pchange[j] = pchange[j+1];
pchange[j+1] = tmp;
flag = 0;
}
}
然后产生报错;
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)