PTA|《C语言程序设计实验与习题指导(第3版)》实验8-1-4 使用函数的选择法排序 (25分)

题目

本题要求实现一个用选择法对整数数组进行简单排序的函数。

函数接口定义:

void sort( int a[], int n );

其中a是待排序的数组,n是数组a中元素的个数。该函数用选择法将数组a中的元素按升序排列,结果仍然在数组a中。

裁判测试程序样例:

#include <stdio.h>
#define MAXN 10

void sort( int a[], int n );

int main()
{
    int i, n;
    int a[MAXN];

    scanf("%d", &n);
    for( i=0; i<n; i++ )
        scanf("%d", &a[i]);

    sort(a, n);

    printf("After sorted the array is:");
    for( i = 0; i < n; i++ )
        printf(" %d", a[i]);
    printf("\n");

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

4
5 1 7 6

输出样例:

After sorted the array is: 1 5 6 7

AC代码

void sort( int a[], int n ){
    int tmp,max;
    for(int i=0;i<n-1;i++){
        max=0;
        for(int j=1;j<n-i;j++){
            if(a[j]>a[max])max=j;
        }
        tmp=a[max];
        a[max]=a[n-i-1];
        a[n-i-1]=tmp;
    }
}
发布了188 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44421292/article/details/104727576