Merge and Sort.

Oct 30, 2012 at 5:43am
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 Oct 30, 2012 at 5:45am
Oct 30, 2012 at 9:18am
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;
    }
}
Oct 30, 2012 at 9:22am
the C is ordered from largest to smallest. i did't notice your claim.
Oct 30, 2012 at 4:05pm
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.
Nov 1, 2012 at 6:39pm
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.