Merge Sort

Hey guys, I have just completed a merge sort program. But i just wondering if anyone may give me any suggestions for my code. Or perhaps correct me if my algorithm is wrong.

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
#include <iostream>

using namespace std;

int* fungsi(int* ptr, int arraySize){
    int* leftSortedArray = NULL;
    int* rightSortedArray = NULL;
    int halfSize = arraySize / 2;

    if(arraySize > 1){
        int* tempLeft = new int[halfSize];
        int* tempRight = new int[arraySize - halfSize];
        int leftIndex = 0, rightIndex = 0;
        int i = 0;

        for(; i < halfSize; i++) tempLeft[i] = ptr[i];
        for(int a = 0; i < arraySize; i++) tempRight[a++] = ptr[i];

        leftSortedArray = fungsi(tempLeft, halfSize);
        rightSortedArray = fungsi(tempRight, arraySize - halfSize);

        for(int i = 0; i < arraySize; i++){
            if((leftIndex == halfSize) || (rightIndex == arraySize - halfSize)){
                if(leftIndex == halfSize) ptr[i] = rightSortedArray[rightIndex++];
                else ptr[i] = leftSortedArray[leftIndex++];
            }
            else{
                if(leftSortedArray[leftIndex] < rightSortedArray[rightIndex]) ptr[i] = leftSortedArray[leftIndex++];
                else ptr[i] = rightSortedArray[rightIndex++];
            }
        }

        delete[] tempLeft;
        delete[] tempRight;
    }

    return ptr;
}

int main(){
    int array_of_int[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    int* sortedArray = fungsi(array_of_int, 11);
    for(int i = 0; i < 10; i++){
        cout << sortedArray[i] << " ";
    }

    return 0;
}
It doesn't look like your algorithm is wrong but here's what I can do for you:

Try looking at any of these:
https://www.tutorialspoint.com/data_structures_algorithms/merge_sort_algorithm.htm
https://en.wikipedia.org/wiki/Sorting_algorithm

I hope that helps,

~ Hirokachi

Last edited on
Well, thank you. Actually, i have already seen that tutorialspoint.com site. But still, thank you for the comment and the suggestions :)
Of course, it was my pleasure and I am sorry I can't be anymore helpful.

Have fun,

~ Hirokachi
Topic archived. No new replies allowed.