Problem 06. 绝对值排序

Problem 06. 绝对值排序

题目简述:

输入n(n<=100)个整数,按照绝对值从大到小排序后输出原数。

解题思路:

    与普通的排序问题类似,只需要在进行比较时用绝对值比较即可。一般排序一般采用升序,而本题采用降序排序。

细节处理:

本题排序采用了冒泡排序,其实还可以采用sort函数进行排序。如下:

……

int com(int a,int b)

{    return abs(a)>abs(b);}

int main()

{    ……

sort(a,a+I,com);

……}

源代码

#include<iostream>
#include<cmath>
using namespace std;
int a[105];
int main()
{
    int n,tem1;
    while(cin>>n)
    {
        if(n==0) break;
        else
        {
        for(int i=0;i<n;i++)
            cin>>a[i];
        for(int k=0;k<n;k++)//冒泡排序
        {
            for(int j=k;j<n;j++)
            {
                if(fabs(a[k])<fabs(a[j]))
                {
                tem1=a[j];//交换两个相邻的数
                a[j]=a[k];
                a[k]=tem1;
                }
            }
        }
        for(int k=0;k<n-1;k++)
        cout<<a[k]<<" ";
        cout<<a[n-1]<<endl;
        }
    }
    return 0;
}

相似题目:插数排序

有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。

源代码:

#include<iostream>
#include<algorithm>
using namespace std;
int a[105];
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        for(int j=0;j<n;j++)
        cin>>a[j];
        if(n==0&&m==0) break;
        else a[n]=m;//将插入的数放入数组的最后
        sort(a,a+n+1);//将插数后的数组进行排序,且按从小到大排序
        for(int k=0;k<n;k++)//将排好序的数组从后往前输出,即从大到小输出
        cout<<a[k]<<" ";
        cout<<a[n]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43397186/article/details/85768774