算法之美--交換排序--冒泡排序

冒泡排序:每次從剩餘的數據對象中選擇一個最近的小於待排序的數據的對象,與待排序的數據交換位置。
特性:不穩定排序

#include<iostream>
#include<stdio.h>
using namespace std;
#define len 20
void main()
{
    int a[len] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 19, 18, 17, 11, 12, 13, 14, 15, 16, 20 };
    for (int i = 0; i < len; i++)//一次取出待排序數據
    {
        //int k = i;
        for (int j = i + 1; j < len;j++)//將取出的數據與後面的所有數據比較,直到找到一個
            if (a[i]>a[j])//如果當前位置i的數據比位置j的數據大,則把二者交換位置
            {
               int temp = a[i];
               a[i] = a[j];
               a[j] = temp;
            }
    }
    for (int l = 0; l < len; l++)//打印
    {
        printf("%d\n", a[l]);
    }

    system("pause");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章