c_cpp 根据给定值的绝对差值对数组进行排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 根据给定值的绝对差值对数组进行排序相关的知识,希望对你有一定的参考价值。

#include<iostream>
#include <bits/stdc++.h>
#include <map>
using namespace std;

int arrange(int a[], int n, int x){
    multimap <int, int> m;

    for(int i = 0; i<n;i++)
        m.insert(pair <int, int> (abs(x-a[i]),a[i]));

    int i = 0;
    for (auto j = m.begin(); j != m.end(); j++)
        a[i++] = (*j).second;
}

int main(){
    int n,x;
    cout << "Enter the no.of elements:";
    cin >> n;
    int a[n];
    cout << "Enter the elements:\n";
    for (int i = 0;i < n; i++)
        cin >> a[i];
    cout << "Enter x:";
    cin >> x;

    arrange(a,n,x);

    for (int i = 0;i < n; i++)
        cout << a[i] << "  ";

}

以上是关于c_cpp 根据给定值的绝对差值对数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章