Process returned (0xc0000005) for rare cases while sorting a vector using sort()

0

I ran the code for random vectors filled with 1 and 2-digit numbers. And there's no error till the size of the array becomes greater than 16. For arrays from size 17 there are few cases where the code fails and returns 'Process returned [some no.] 0xc0000005 '.

So my code basically outputs the largest number formed by shuffling given numbers(can be a 2 or more digit number as well). Eg. Input: 23 39 92 6. Output: 9263923. And for that I've used a sort function to arrange the given numbers in the required order. I defined the comparator function for it in the following manner:


bool sortcomp(int a,int b){

    /*cout<<"comparing:"<<a<<" & "<<b;
    cout<<endl;*/

    int a1=a;           //a1 is the First digit in a
    int b1=b;           //b1 is the First digit in b
    int dig1=1;         //Number of digits in a
    int dig2=1;         //Number of digits in b
    
    while(a1/10>0){     
        a1=a1/10;
        dig1++;
    }
    while(b1/10>0){
        b1=b1/10;
        dig2++;
    }
    
    if(a1>b1){
        return true;
    }
    if(b1>a1){
        return false;
    }
    if(a/10==0&&b/10==0){
        return true;
    }
    
    if(a/10>0){
        int x=1;
        while(dig1>1){
            x*=10;
            dig1--;
        }
        a-=a1*x;
    }
    if(b/10>0){
        int x=1;
        while(dig2>1){
            x*=10;
            dig2--;
        }
        b-=b1*x;
    }
    return sortcomp(a,b);
}

called using: sort(arr.begin(),arr.end(),sortcomp);

Also I used cout<<"comparing:"<<a<<" & "<<b; in the comparator to check what's happening. And what I saw is it starts comparing garbage values for the cases where it fails.

Examples of the failed cases:

n=17: 40 99 97 7 54 4 37 85 99 92 13 12 82 83 51 29 37

n=18: 64 9 71 67 56 93 80 89 13 9 23 1 43 70 57 55 37 91

n=20: 84 98 85 88 97 22 3 43 15 55 98 18 34 29 53 18 85 18 98 16

I have no clue what I'm doing wrong here. Please help. Thanks!

c++
arrays
sorting
vector
asked on Stack Overflow Sep 30, 2020 by Sanjay Vasnani • edited Sep 30, 2020 by Sanjay Vasnani

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0