Merge Sort algorithm

Hi! What could be the best algorithm for "Merge Sort" where the memory must be used "most effectively"? I just know the standard way to do this, but that's not the most effective way how to use the memory.
This is the only variant which I know:
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
#include <iostream>
using namespace std;
int main() {
    int arr1[20]= {0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    int arr2[14]= {0,23,25,27,29,31,33,35,37,39,40,41,42,43};
    int arr3[34];
    int indexA=0, indexB=0, indexC=0;

    while((indexA<20) && (indexB<14)) {
        if(arr1[indexA] < arr2[indexB]) {
            arr3[indexC] = arr1[indexA];
            indexA++;
        }
        else {
            arr3[indexC] = arr2[indexB];
            indexB++;
        }
        indexC++;
    }

    while(indexA<20) {
        arr3[indexC] = arr1[indexA];
        indexA++;
        indexC++;
    }

    while(indexB<14) {
        arr3[indexC] = arr2[indexB];
        indexB++;
        indexC++;
    }

    for (int i=0; i<34; i++)
	cout << arr3[i] << " ";
return 0;
}


Can anyone please advise me a better algorithm for "Merge Sort" which uses the memory in "more effective" way? It can also not be with arrays.

Thank You very much!
Last edited on
as a matter of fact, i'm working on a merge sort assignment right now, but my assignment is a bit different. are you familiar with a data structure called a linked list? if you used a linked list instead of arrays, you could conserve memory if done properly. although i must admit you should take what i say with a grain of salt; i have not actually written a merge sort program that uses linked lists, but it just seems conceptually like the best way to do it, if your goal is to conserve memory.
Yes, I am familiar with a linked list.
First, I need 2 linked lists and then combine them into the third linked list?
Because, how much I know, "merge sort" just stick together 2 already sorted data structures into the 3rd one and then sort that 3rd data structure. Or am I wrong?

How do you think - how could I use linked lists here?

Thanks!
Last edited on
you have the basic idea down.
doing it your way, you are storing 34*2 integers.

if you used linked lists, here is roughly what you could do:
-compare first item on list 1 & 2
-whichever one is higher, remove it from it's list and put it on list 3.
-rinse & repeat


i'm assuming you are allowed to start with two already sorted data structures?
Topic archived. No new replies allowed.