Need to merge two arrays, and sort them

Hi all,

I need to merge two arrays. I already have a bool function that should find out whether or not a particular array is sorted, and I call it inside my merge function. If it is not, I exit the program. If it is, then I want to merge the two arrays, a and b, onto the combo array. Also, for the sake of this particular program, I need to make sure the sorting is done when it is being added to combo, not after. My problem right now is that when I run the sort function inside my merge function, the conditional statement is acting as if one of them is not sorted.

Thanks for looking.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

#include <iostream>
#include <cstdlib>

using namespace std;

bool die( const string & msg ){

        cerr <<endl <<"Fatal error: " <<msg <<endl;
        exit( EXIT_FAILURE );
}

bool sorted( const unsigned a[], unsigned elements ){

for (unsigned i = 0; i < elements; i++){

    if (a[i] > a[i+1]){
        return false;
        break;
    }}
        return true;
    }

void merge(unsigned combo[], const unsigned a[], unsigned aElements, const unsigned b[], unsigned bElements ){
    
    if (sorted(a, aElements) && sorted(b, bElements)){
        
        for (unsigned i = 0; i < aElements; i++){
            
            combo[i] = a[i];
            
        }
        
        for (unsigned k = 0; k < bElements; k++){
            
            if (b[k] > b[k+1]){
                combo[k] += b[k];
            }
            
        }
        
        
    }
    
    else{
        
        die("One or more arrays not sorted");
        
    }
}

int main(){

 unsigned aElements = 4;
 unsigned bElements = 4;

 unsigned a[] = {0, 1, 2, 3};
 unsigned b[] = {3, 4, 5, 6};
 unsigned combo[8] = {}

merge(combo, a, aElements, b, bElements);

return 0;
}

 
Last edited on
Line 15: last iteration will have i==elements-1
Line 17: access a[i+1] == a[elements-1+1] == a[elements]
That is an "out of range" error.
Topic archived. No new replies allowed.