冒泡排序`
#include <stdio.h>
void swap (int a[], int i, int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void printA (int *a, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf ("%-4d", a[i]);
}
printf ("\n");
}
//冒泡排序
int main()
{
int a[10] = {2,3,4,1,0,9,5,6,7,8};
int len = sizeof(a) / sizeof(a[0]);
int i,j;
for (i = 0; i < len - 1; i++)
{
for (j = 0; j < len-i-1; j++)
{
if(a[j] > a[j + 1])
{
swap (a, j, j+1);
}
}
}
printA (a,10);
}
鸡尾酒排序(升级版冒泡排序)
int main1 ()
{
int a[10] = {2,3,4,1,0,9,5,6,7,8};
int len = sizeof(a)/sizeof(a[0]);
int left = 0;
int right = len - 1;
int i;
while (left < right)
{
//从左到右选出最大的数放右边
for (i = left; i < right; i++)
{
if (a[i] > a[i+1])
{
swap (a, i, i+1);
}
}
right--;
//从右到左选出最小的数放左边
for (i = right; i > left; i--)
{
if (a[i-1] > a[i])
{
swap (a , i, i-1);
}
}
left++;
}
printA (a , 10);
}
选择排序
#include <stdio.h>
void swap (int a[], int i, int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void printA (int *a, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf ("%-4d", a[i]);
}
printf ("\n");
}
int main ()
{
int a[10] = {2,3,4,1,0,9,5,6,7,8};
int len = sizeof(a) / sizeof(a[0]);
int i,j;
for (i = 0; i < len - 1; i++)
{
int min = i;
for (j = i + 1; j < len ; j++)
{
if (a[min] > a[j])
{
min = j;
}
}
if (min != i)
{
swap(a, i, min);
}
}
printA (a , 10);
}