C語言 | 冒泡排序算法

1.算法思路

目的:將輸入的數組按照從小到大冒泡排序。算法

思路:
① 從第1個數開始, 依次與後一個數比較,將最大的一個數放在最後;
② 繼續從第1個數開始,依次與後一個比較,將最大的一個數倒數第二個;
③ 依次類推;數組

2. 算法實現
int bubble(int a[], int n)
{
    int temp;
    int i,j;

    for(i = 0; i< n-1;i++)
    {
        for(j = 0;j < n-1-i;j++)
        {
            if(a[j] > a[j+1])
            {
                temp = a[j+1];
                a[j+1] = a[j];
                a[j] = temp;
            }
        }
    }
    return 0;
}
3. 算法測試
/** * @brief 測試冒泡程序 * @author mculover666 * @date 2020/04/09 */

#include<stdio.h>

int bubble(int a[], int n);

int main()
{
    int i;
    int nums[10];

    for(i = 0;i < 10;i++)
    {
        nums[i] = 9-i;
        printf("%2d ", nums[i]);
    }
    printf("\n");

    //排序功能
    bubble(nums, 10);

    //打印排序後的數
    for(i = 0;i < 10;i++)
    {
        printf("%2d ", nums[i]);
    }
    printf("\n");

    return 0;
}

int bubble(int a[], int n)
{
    int temp;
    int i,j;

    for(i = 0; i< n-1;i++)
    {
        for(j = 0;j < n-1-i;j++)
        {
            if(a[j] > a[j+1])
            {
                temp = a[j+1];
                a[j+1] = a[j];
                a[j] = temp;
            }
        }
    }
    
    return 0;
}

編譯:bash

gcc test.c -o test.o

執行結果:
ide

相關文章
相關標籤/搜索