C語言氣泡排序將一個數組按照從小到大進行排序
阿新 • • 發佈:2019-01-24
例如 int a[10] = {0,5,2,3,6,9,8,7,4,1}
對其10個整數由小到大進行排序
思想:氣泡排序
實現一:
#include<stdio.h>
int main()
{
int i = 0;
int a[10] = {0,5,2,3,6,9,8,7,4,1};
int j = 0;
int tmp = 0;
int m = sizeof(a) / sizeof(a[0]); //s陣列大小
for (i=0; i<m-1; i++) //比較m-1次
{
for (j = 0; j < m-i-1 ; j++) // 最後一次比較a[m-i-1]與a[m-i-2]
{
if (a[j]>a[j+1]) //如果a[j]比a[j+1]大則交換內容
{
tmp = a[j+1];
a[j+1] = a[j];
a[j] = tmp;
}
}
}
for (i=0; i < m; i++)
{
printf(" %d ", a[i]); //列印
}
printf(" \n ");
return 0;
}
實現二:
自定義sort函式
#include<stdio.h>
void sort(int a[], int m)
{
int i = 0;
int j = 0;
int tmp = 0;
for (i = 0; i<m - 1; i++)
{
for (j = 0; j < m - i - 1; j++)
{
if (a[j]>a[j + 1])
{
tmp = a[j + 1 ];
a[j + 1] = a[j];
a[j] = tmp;
}
}
}
}
int main()
{
int i = 0;
int a[10] = {0,5,2,3,6,9,8,7,4,1};
int m = sizeof(a) / sizeof(a[0]);
sort(a, m);
for (i=0; i < m; i++)
{
printf(" %d ", a[i]);
}
printf(" \n ");
return 0;
}