Merge and Sort.

How do you Merge a list of numbers in two files and input them in a third file witch has them ordered from smallest to largest.. I haven't learned about vectors in my class yet and this is chapter six in my c++ book (which I read) and no vectors included. Is there another way to do this without using a vector?
Last edited on
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
67
68
69
70
71
typedef struct node 
{
    int data;
    struct node *next;
} Slink;


void merge(Slink *A, Slink *B, Slink *C)
{
    Slink *pa = NULL;  
    Slink *qa = NULL;  
    Slink *pb = NULL;  
    Slink *qb = NULL;  
	
    
    C = A;
    C->next = NULL;
   
    pa = A->next;
    pb = B->next;
    free(B);
    B = NULL;
	
   
    while (pa && pb)
    {
        if (pa->data <pb->data)
        {
            qa = pa;
            pa = pa->next;
            _insert(qa, C);
        }
        else
        {
            qb = pb;
            pb = pb->next;
            _insert(qb, C);
        }
    }
	
   
    while (pa)
    {
        qa = pa;
        pa = pa->next;
        _insert(qa, C);
    }
   
    while (pb)
    {
        qb = pb;
        pb = pb->next;
        _insert(qb, C);
    }
}


void _insert(Slink *qNode, Slink *C)
{
    
    if(!(C->next) || C->next->data < qNode->data)
    {
        qNode->next = C->next;
        C->next = qNode;
    }
    else
    {
        free(qNode);
        qNode = NULL;
    }
}
the C is ordered from largest to smallest. i did't notice your claim.
Assuming the two input files are sorted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Open input files. (A & B)
Open output file. (C)

read in number A (a)
read in number B (b)

while ( there are numbers in file A and file B )
{
     if ( a > b )
         write b to C
         read number in from B
     else
          write a to C
          read number in from A
}

read in numbers from whichever file (A or B) which still has numbers in it.
write them out to C.


That should be enough to get you started.
I figured it out thank you i used if-else statements and boolean expressions like "Cire" did above me ..
Topic archived. No new replies allowed.