C语言是学习计算机基础,暑假一直在学Java,开学了数据结构上机,老师让编一个实现N个整数排序,
并插入一个整数的小程序,可是我整节课都没搞定。郁闷了许久,觉得自己太过舍本逐末了,基础都忘光了。
咳~~~~于是一阵恶补。好好看了看排序,总结及源码如下:
冒泡排序:
#include
"
stdio.h
"
main()
{
int i,j,temp,s;
int a[ 10 ];
printf( " 请输入10个整数: " );
for (i = 0 ;i < 10 ;i ++ )
scanf ( " %d, " , & a[i]);
for (j = 0 ;j <= 9 ;j ++ )
{ for (i = 0 ;i < 10 - j;i ++ )
if (a[i] > a[i + 1 ])
{ temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;}
}
printf( " 冒泡排序后的数列为: " );
for (i = 0 ;i < 10 ;i ++ )
printf( " %3d " ,a[i] );
printf( " \n " );
scanf( " %d " , & s); // 防止运行窗口迅速关闭
}
main()
{
int i,j,temp,s;
int a[ 10 ];
printf( " 请输入10个整数: " );
for (i = 0 ;i < 10 ;i ++ )
scanf ( " %d, " , & a[i]);
for (j = 0 ;j <= 9 ;j ++ )
{ for (i = 0 ;i < 10 - j;i ++ )
if (a[i] > a[i + 1 ])
{ temp = a[i];
a[i] = a[i + 1 ];
a[i + 1 ] = temp;}
}
printf( " 冒泡排序后的数列为: " );
for (i = 0 ;i < 10 ;i ++ )
printf( " %3d " ,a[i] );
printf( " \n " );
scanf( " %d " , & s); // 防止运行窗口迅速关闭
}
选择排序:
Code
实现N个整数排序,并插入一个整数源码:
#include
<
stdio.h
>
main(){
int n;
int a[ 100 ];
int i,j,k,t,x,s;
printf( " 输入数列长度:\n " );
scanf( " %d " , & n);
printf( " 请输入%d个整数:\n " ,n);
for (i = 0 ;i < n;i ++ ){
scanf( " %d " , & a[i]);
}
for (i = 0 ;i < n;i ++ ){ // 排序
k = i;
for (j = i;j < n - 1 ;j ++ ){
if (a[k] > a[j + 1 ]){
k = j + 1 ;
}
}
if (k != i){
t = a[i];
a[i] = a[k];
a[k] = t;
}
}
printf( " \n " );
printf( " 排序后的数列:\n " );
for (i = 0 ;i < n;i ++ ){
printf( " %d " ,a[i]);
}
printf( " \n " );
printf( " 请输入要插入的数: " );
scanf( " %d " , & x);
for (i = 0 ;i < n;i ++ ){
if (x > a[i] && x < a[i + 1 ]){
k = i + 1 ;
break ;
}
}
for (i = n;i > k;i -- ){
a[i] = a[i - 1 ];
}
a[k] = x;
printf( " 插入%d后的排序数列为: " ,x);
for (i = 0 ;i <= n;i ++ ){
printf( " %d " ,a[i]);
}
scanf( " %d " ,s); // 同上
}
main(){
int n;
int a[ 100 ];
int i,j,k,t,x,s;
printf( " 输入数列长度:\n " );
scanf( " %d " , & n);
printf( " 请输入%d个整数:\n " ,n);
for (i = 0 ;i < n;i ++ ){
scanf( " %d " , & a[i]);
}
for (i = 0 ;i < n;i ++ ){ // 排序
k = i;
for (j = i;j < n - 1 ;j ++ ){
if (a[k] > a[j + 1 ]){
k = j + 1 ;
}
}
if (k != i){
t = a[i];
a[i] = a[k];
a[k] = t;
}
}
printf( " \n " );
printf( " 排序后的数列:\n " );
for (i = 0 ;i < n;i ++ ){
printf( " %d " ,a[i]);
}
printf( " \n " );
printf( " 请输入要插入的数: " );
scanf( " %d " , & x);
for (i = 0 ;i < n;i ++ ){
if (x > a[i] && x < a[i + 1 ]){
k = i + 1 ;
break ;
}
}
for (i = n;i > k;i -- ){
a[i] = a[i - 1 ];
}
a[k] = x;
printf( " 插入%d后的排序数列为: " ,x);
for (i = 0 ;i <= n;i ++ ){
printf( " %d " ,a[i]);
}
scanf( " %d " ,s); // 同上
}
全部代码都测试通过,正确无误!
本文转自施杨博客园博客,原文链接:http://www.cnblogs.com/shiyangxt/archive/2008/09/03/1283403.html,如需转载请自行联系原作者