方法一(不使用函数解决)
#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>
int main()
{int arr[]={15,52,23,0,5,6,45,8,9,10};int i=0;int j=0;for ( i = 0; i < 9; i++){int flag=1; //flag判断数组元素是否有序,这里先假设有序for ( j = 0; j < 9-i; j++){if (arr[j]>arr[j+1]){int tmp=arr[j];arr[j]=arr[j+1];arr[j+1]=tmp;flag = 0; //元素不是有序}}if(flag ==1){break;}}printf("The sorted number :\n");for ( i = 0; i < 10; i++){printf("%d ",arr[i]);}printf("\n");return 0;
}
方法二(函数解决)
#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>
void bubble_sorted(int arr[],int sz)
{int i = 0;for(i=0;i<sz;i++){int flag=1;int j = 0;for(j=0;j<sz-1-i;j++){if(arr[j]>arr[j+1]){int temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;flag=0;}}if(flag == 1){break;}}
}
int main()
{int arr[]={15,52,23,0,5,6,45,8,9,10};int i=0;int sz=sizeof(arr)/sizeof(arr[0]);bubble_sorted(arr,sz);printf("The sorted number :\n");for(i=0;i<sz;i++){printf("%d ",arr[i]);}printf("\n");return 0;
}