美文网首页
【MAC 上学习 C++】Day 49-3. 实验8-1-4 使

【MAC 上学习 C++】Day 49-3. 实验8-1-4 使

作者: RaRasa | 来源:发表于2019-10-12 20:30 被阅读0次

实验8-1-4 使用函数的选择法排序 (25 分)

1. 题目摘自

https://pintia.cn/problem-sets/13/problems/540

2. 题目内容

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

函数接口定义:

void sort( int a[], int n );
其中a是待排序的数组,n是数组a中元素的个数。该函数用选择法将数组a中的元素按升序排列,结果仍然在数组a中。

输入样例:

4
5 1 7 6

输出样例:

After sorted the array is: 1 5 6 7

3. 源码参考
#include <iostream>

using namespace std;

#define MAXN 10

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

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

    cin >> n;
    for( i=0; i<n; i++ )
    {
      cin >> a[i];
    }

    sort(a, n);
    cout << "After sorted the array is:";
    for( i = 0; i < n; i++ )
    {
      cout << " " << a[i];
    }

    cout << endl;

    return 0;
}

void sort( int a[], int n )
{
  int i, j, t;

  for(i = 0; i < n; i++)
  {
    for(j = i + 1; j < n; j++)
    {
      if(a[i] > a[j])
      {
        t = a[i];
        a[i] = a[j];
        a[j] = t;
      }
    }
  }

  return;
}

相关文章

网友评论

      本文标题:【MAC 上学习 C++】Day 49-3. 实验8-1-4 使

      本文链接:https://www.haomeiwen.com/subject/ncsgectx.html