冒泡排序(C语言实现)

冒泡排序

#include <stdio.h>
void bubble_sort(int *a, int length)
{
    int i, j, temp ;
    
    for(i = 0; i <= length-2; i++)//循环一次找出一个最大元素移动到最后
        for(j=0; j<=length-2-i; j++)//遍历数组将最大的数组移动到最后,每一次循环在上一次遍历找出的最大元素之间一个位置 
            if(a[j]>a[j+1]){
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }       
}
int main()
{
    int array[] = {6, 4, 10, -7, 23, 4, 8, 13,77};
    int len = (int)sizeof(array) / sizeof(int); 
    bubble_sort(array,len);
    int i;
    for(i=0; i<=len-1; i++) printf("%d ",array[i]); 
    return 0;
}

输出结果如下:

-7 4 4 6 8 10 13 23 77
--------------------------------
Process exited after 0.2333 seconds with return value 0
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/qq_41580631/article/details/88417359