- #include <stdio.h>
- void bubbleSort(int *list,int index)
- {
- int i,j;
- int change=0;/*记录数值是否有交换位置*/
- int temp;/*数值交换时的暂存变量*/
- while(!change)
- {
- change=1;
- for(j=index;j>0;j--)
- {
- for(i=0;i<j-1;i++)
- {
- if(list[i]>list[i+1])
- {
- temp = list[i+1];
- list[i+1] = list[i];
- list[i] = temp;
- change = 0;
- /*打印目前的排序结果*/
- printf("/nCurrent sorting result:");
- for(i=0;i<index;i++)
- printf("%d ",list[i]);
- }
- }
- }
- }
- }
- int main()
- {
- int list[20];
- int i,index;
- int node;
- printf("/n Please input the values you want to sort(0 for Exit):/n");
- index = 0;
- /*读取数据存到数组中*/
- scanf("%d",&node);
- while(node!=0)
- {
- list[index] = node;
- index++;
- scanf("%d",&node);
- }
- bubbleSort(list,index);
- printf("/n Final sorting result:");
- for(i=0;i<index;i++)
- printf("%d ",list[i]);
- }
以上为冒泡排序法。