打算认真研究算法,所以,把这些基本算法都写出来,练练手。部分内容引用:http://ahalei.blog.51cto.com/4767671/1364401(坐在马桶上看算法2)
冒泡算法特征:每次循环只能让一个数据排到正确的位置上。因此,n个数据的排序,必须执行n-1次循环(让n-1个数据排到正确位置上,剩下的那个自然是最小的,排在最后,不用循环)。
冒泡算法缺陷:不实用。冒泡排序的核心部分是双重嵌套循环。不难看出冒泡排序的时间复杂度是O(N2)。这是一个非常高的时间复杂度。冒泡排序早在1956年就有人开始研究,之后有很多人都尝试过对冒泡排序进行改进,但结果却令人失望。如Knuth(Donald E. Knuth中文名为高德纳,1974年图灵奖获得者)所说:“冒泡排序除了它迷人的名字和导致了某些有趣的理论问题这一事实之外,似乎没有什么值得推荐的。”你可能要问:那还有没有更好的排序算法呢?请看下一篇快速排序。
#include <stdio.h>
int main()
{
int sort[20],record,num,i,j,temp;
printf("how many number will you input(1~20):\n");
scanf("%d",&num);
printf("Let's begin to input num between 0~1000:\n");
for(i=0;i<num;i++)
{
scanf("%d",&record);
sort[i]=record;
}
printf("the sorting result is:");
for(i=0;i<num;i++)
{
//we can figure out the biggest num after every loop
for(j=i+1;j<num;j++)
{
if(sort[j]>sort[i])
{
temp = sort[i];
sort[i]=sort[j];
sort[j]=temp;
}
}
printf("%d ",sort[i]);
}
printf("\n");
getchar();
return 0;
}
运行结果
norton@norton-laptop:~/learning/sample code/algrithm/sort/bubble$ ./bubble.o
how many number will you input(1~20):
3
Let's begin to input num between 0~1000:
10
20
30
the sorting result is:30 20 10
norton@norton-laptop:~/learning/sample code/algrithm/sort/bubble$ ./bubble.o
how many number will you input(1~20):
4
Let's begin to input num between 0~1000:
20
20
20
20
the sorting result is:20 20 20 20
下面为每个分数加上名字标签,让分数有具体意义,通过增加结构体实现。
#include <stdio.h>
struct student
{
int score;
char name[20];
};
int main()
{
int num,i,j;
struct student class[20];
struct student temp;
printf("how many record will you input(1~20):\n");
scanf("%d",&num);
printf("Please input the record like this wangqi 100:\n");
for(i=0;i<num;i++)
{
scanf("%s %d",class[i].name,&(class[i].score));
}
printf("the sorting result is:\n");
printf("Rank Name Score\n");
for(i=0;i<num;i++)
{
//we can figure out the biggest num after every loop
for(j=i+1;j<num;j++)
{
if(class[j].score>class[i].score)
{
temp = class[i];
class[i]=class[j];
class[j]=temp;
}
}
printf("No.%2d %8s %8d \n",i,class[i].name,class[i].score);
}
printf("\n");
getchar();
return 0;
}
运行结果如下
norton@norton-laptop:~/learning/sample code/algrithm/sort/bubble$ ./bubble_score.o
how many record will you input(1~20):
5
Please input the record like this wangqi 100:
ken 80
jack 90
norton 95
koben 100
allen 99
the sorting result is:
Rank Name Score
No. 0 koben 100
No. 1 allen 99
No. 2 norton 95
No. 3 jack 90
No. 4 ken 80