2025年3月13日 星期四 甲辰(龙)年 月十二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言选择排序代码

时间:01-03来源:作者:点击数:75

下面的程序,将会提醒你输入一个整数数组,然后使用选择排序从小到大排列。

关于选择排序你也可以查看:C语言选择排序算法及代码

注意:代码被分成三个文件,培养大家的工程化思维。

注意:下面的程序在 VC6.0 下编译不能通过,因为在 VC6.0 中数组长度不能为变量和不定值;请在 Linux 的 GCC 或 Window 的 MinGW 下编译。

笔者顺便推荐一款国产C语言开发神器 -- C-Free 5.0 -- 默认编译器是 MinGW,可以随意切换多个编译器,详情请查看:C-Free 5.0下载[带注册码][赠送破解版][最性感的C、C++开发工具IDE]

selectionMain.c -- 主文件

  • #include <stdio.h>
  • #include "intArray.h"
  • #define NMAX 10
  • int main(void) {
  • int x[NMAX];
  • int hmny;
  • int who;
  • int where;
  • hmny = getIntArray(x, NMAX, 0);
  • if (hmny==0)
  • printf("This is the empty array!\n");
  • else{
  • printf("The array was: \n");
  • printIntArray(x,hmny);
  • selectionSort(x,hmny);
  • printf("The sorted array is: \n");
  • printIntArray(x,hmny);
  • }
  • }

intArray.h -- 头文件,对函数进行声明

  • extern int getIntArray(int a[], int nmax, int sentinel);
  • extern void printIntArray(int a[], int n);
  • extern void selectionSort(int a[], int n);

intArray.c -- 函数的实现

  • // n 为数组 a 中元素的个数;数组元素将会被打印输出,5 个一行
  • void printIntArray(int a[], int n)
  • {
  • int i;
  • for (i=0; i<n; ){
  • printf("\t%d ", a[i++]);
  • if (i%5==0)
  • printf("\n");
  • }
  • printf("\n");
  • }
  • // 读取最多 nmax 个整数放入数组 a,遇到特性值结束读取
  • int getIntArray(int a[], int nmax, int sentinel)
  • {
  • int n = 0;
  • int temp;
  • do {
  • printf("Enter integer [%d to terminate] : ", sentinel);
  • scanf("%d", &temp);
  • if (temp==sentinel) break;
  • if (n==nmax)
  • printf("array is full\n");
  • else
  • a[n++] = temp;
  • }while (1);
  • return n;
  • }
  • // 使用选择排序将数组 a 的前 n 个元素从小到大排列
  • void selectionSort(int a[], int n)
  • {
  • int lcv;
  • int rh;
  • int where;
  • int temp;
  • for(rh=n-1;rh>0;rh--){
  • where = 0;
  • for (lcv=1;lcv<=rh;lcv++)
  • if (a[lcv]>a[where])
  • where = lcv;
  • temp = a[where];
  • a[where] = a[rh];
  • a[rh] = temp;
  • }
  • }

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门