# Error in a Quick Sort recursion

``````#include <iostream>
using namespace std;

struct HopKeo {
int chiso;
long long keo;
};

long long n,m;
HopKeo a[100001];
bool sosanh(HopKeo x,HopKeo y){
if (x.keo>y.keo) return true;
else if (x.keo==y.keo && x.chiso > y.chiso) return true;
return false;
}
bool chiso(HopKeo x, HopKeo y){
if (x.chiso>y.chiso) return true;
return false;
}
void sort(int l,int r){
HopKeo x = a[(l+r)/2];
int i = l;
int j = r;
while (i<=j){
while (sosanh(x,a[i])) i++;
while (sosanh(a[j],x)) j--;
if (i<=j){
HopKeo t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
}
if (i<r) sort(i,r);
if (l<j) sort(l,j);
}
void sortchiso(int l,int r){
HopKeo x = a[(l+r)/2];
int i = l;
int j = r;
while (i<=j){
while (chiso(x,a[i])) i++;
while (chiso(a[j],x)) j--;
if (i<=j){
HopKeo t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
}
cout <<i <<" " <<r <<endl;
if (i<r) sort(i,r);
if (l<j) sort(l,j);
cout <<l <<" " <<j <<" " <<i <<" " <<r <<endl;
}
void XuLi(){
scanf("%lld %lld\n",&n,&m);
for (int i = 1;i<=n;i++){
scanf("%lld ",&a[i].keo);
a[i].chiso = i;
}
while (m>0){
sort(1,n);
if (a[2].keo == a[1].keo) {
a[1].keo++;
m--;
}
else {
long long diff = a[2].keo-a[1].keo;
if (diff<m){
a[1].keo+=diff;
m-=diff;
}
else {
a[1].keo+=m;
m = 0;
}
}
}
sortchiso(1,n);
for (int i = 1;i<=n;i++){
cout <<a[i].keo <<" ";
}
}

int main(){
/*freopen("candy1051.inp","r",stdin);
freopen("candy1051.out","w",stdout);*/
XuLi(); return 0;
}
``````

This is a C++ code. Anyway, when I use this test:

``````N = 4 M = 4
2 1 4 2
``````

The exercise is that given N and M. For N elements in array, distribute 1 unit from M to the element which has lowest value (keo), if there are multiple elements which have the same lowest value, distribute it to the element which has the lowest indicator (chiso, in struct HopKeo).
When I tried to use sortchiso to sort the indicator, it just stop sorting.
Can anyone help me?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.