冒泡排序:
#include <stdio.h>
#include <stdlib.h>
#define N 10
static void sort1(void)
{
int i = 0, j = 0, tmp;
int a[N] = {12,8,45,30,98,67,2,7,68,11};
for(i = 0; i < N; i++)
{
printf("%d ",a[i]);
}
printf("\n");
for(i = 0; i < N - 1; i++)//需要进行N-1次冒泡:从0 -> N-2
{
for(j = 0; j < N - 1 - i; j++)//每次冒泡需比较个数为N-1-i
{
if(a[j] > a[j+1])
{
tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
for (i = 0; i < N; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
选择法:
static void sort2 (void)
{
int i, j, k, tmp;
int a[N] = {23, 45, 90, 76, 13, 55, 78, 45, 3, 8};
for(i = 0; i < sizeof(a)/sizeof(a[i]); i++)
printf("%d ",a[i]);
printf("\n");
for( i = 0; i < N-1; i++)//需进行N-1次选择
{
k = i;
for(j = i + 1; j < N; j++)
{
if(a[j] < a[k])//比较a[k]即a[i]与a[j]的大小
k = j; //当a[k]>a[j]时,让a[k]=a[j]
}
if( i != k)//上面a[k]即a[j]与a[i]不相等后,交换两个值,最终保证a[i]的值最小
{
tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
}
for(i = 0; i < sizeof(a)/sizeof(a[i]); i++)
printf("%d ", a[i]);
printf("\n");
}
分析的有点笼统,记录一下代码,方便以后看