排序功能在C ++中无法按预期工作

时间:2018-09-30 05:47:20

标签: c++ arrays sorting

我将int数组重新排列,使得所有负数都在数组的右侧,所有正数和零都在数组的左侧, 而不更改给定数组中正元素和负元素的顺序。

例如:-

n = 18

给定的输入:34 99 40 70 -28 27 -49 96 -18 -90 -6 -2 92 82 53 -47 -98 -53

预期输出:34 99 40 70 27 96 92 82 53 -28 -49 -18 -90 -6 -2 -47 -98 -53

我的输出:99 40 70 34 27 27 96 53 82 92 -53 -98 -47 -2 -6 -90 -18 -49 -28 -84

#include<algorithm>
#include<iostream>
using namespace std;
bool comp(int a,int b){
    if((a>=0 && b>=0) || (a<0 && b<0)|| (a<0 && b>=0)) return false;
    if(a>=0 && b<0) return true;
}
int main(){
    int n;
    cin>>n;
    int a[n];
    for(int j=0;j<n;j++)cin>>a[j];
    sort(a,a+n,comp);
    for(int j=0;j<n;j++)cout<<a[j]<<" ";
return 0;
}

为什么它没有按预期重新排列?我找不到任何错误。

1 个答案:

答案 0 :(得分:1)

您的comp()可以重写为

bool comp(int a, int b)
{
    return ( a >= 0 && b < 0 );
}

但是问题是std::sort()不保证它会保留被认为相等的元素的顺序。请改用std::stable_sort()

相关问题