-2

I am new to programming, and I have been learning about Merge Sort Algorithm, I wrote the following code:

#include <iostream>
using namespace std;
void Merge(int *arr1, int i, int m, int n, int j)
{
    int sizeOfNewArray = j - i + 1; 
    int sizeOfFirstArray = m - i + 1;
    int sizeOfSecondArray = j - n + 1;
    int *finalArray = new int[sizeOfNewArray];
    int *k = &finalArray[i];
    int *ptr1 = &arr1[i];
    int *ptr2 = &arr1[n];
    while (i < sizeOfFirstArray && j < sizeOfSecondArray)
    {
        if (*ptr1 >= *ptr2)
        {
            *k = *ptr1;
            i++;
            k++;
        }
        else if (*ptr1 < *ptr2)
        {
            *k = *ptr2;
            j++;
            k++;
        }
    }
    while (i < sizeOfFirstArray)
    {
        *k = *ptr1;
        i++;
        k++;
    }
    while (j < sizeOfSecondArray)
    {
        *k = *ptr2;
        j++;
        k++;
    }
}
void MergeSort(int *arr1, int i, int j)
{
    if (i != j)
    { //i represnts first index of array, j represents last index of array
        int m = (i + j) / 2;
        MergeSort(arr1, i, m);
        MergeSort(arr1, m + 1, j);
        Merge(arr1, i, m, m + 1, j);
    }
    if (i == j)
    {
        return;
    } 
}
int main()
{
    int arr[] = {8, 6, 7, 1, 2, 4, 3, 5};
    MergeSort(arr, 0, 7);
    for (int i = 0; i < 8; i++)
    {
        cout << arr[i] << endl;
    }
    return 0;
}

According to me, this program should return the sorted array 1,2,3,4,5,6,7,8. However,on executing this code, it prints

8
6
7
1
2
4
3
5

I have tried debugging the code, but I am not able to find out what the error is. Can someone please have a look at the code, and tell me where is the error?

Apologies in advance for any silly error and thanks for taking out your time and concern.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Your `arr` array hasn't been changed ever, so it's not sorted. Have you checked the wiki: https://en.wikipedia.org/wiki/Merge_sort , the algorithm here is much clean and performant (I can't confirm your algorithm will works). – prehistoricpenguin Jun 30 '21 at 03:03
  • I tried to edit my code, here's the new code: https://ide.codingblocks.com/s/581287 , but it is printing garbage values, please I request you to have a look at the code again and point out any error if it is still there. @prehistoricpenguin – newprogrammer Jun 30 '21 at 03:25
  • @newprogrammer `int *finalArray = new int[sizeOfNewArray];` -- What do you finally do with this allocated memory? I don't see you doing anything with it *after* the `Merge` function is called. It just sits there to leak memory. – PaulMcKenzie Jun 30 '21 at 03:44
  • @PaulMcKenzie I am not new to programming, I am new to Data Structures and Algorithms. And yes, I am following a course but I wasn't able to figure out the error in my code. – newprogrammer Jun 30 '21 at 03:51
  • @newprogrammer Also, instead of `int arr[] = {8, 6, 7, 1, 2, 4, 3, 5};`, how about something much smaller: `int arr[] = {8, 6, 7, 1};` -- Then follow the code with something smaller to see where you are going wrong. If it doesn't work with 4 numbers, it isn't going to work with 8 numbers. – PaulMcKenzie Jun 30 '21 at 03:51
  • @PaulMcKenzie I intend to use the memory allocated for finalArray, for storing my final array. Please see the link at this code: https://ide.codingblocks.com/s/581287, not the one in the original post – newprogrammer Jun 30 '21 at 03:52
  • I am editing the original post as well, and I will post the code there – newprogrammer Jun 30 '21 at 03:53
  • @PaulMcKenzie Please see the edited post – newprogrammer Jun 30 '21 at 03:55
  • @PaulMcKenzie Can you tell me the error in the code in the edited post? – newprogrammer Jun 30 '21 at 03:55
  • *I have tried debugging the code, but I am not able to find out what the error is.* -- What do you actually mean by "debugging the code"? Did you run the code, step by step, in the debugger? – PaulMcKenzie Jun 30 '21 at 03:56
  • @PaulMcKenzie No, I tried to dry run it on my notebook . – newprogrammer Jun 30 '21 at 03:57
  • 1
    @newprogrammer [What is a debugger, and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). Also, programming isn't about just writing code, hoping it works, and if anything goes wrong, post a question on StackOverflow and sit back and wait for someone else to debug the code. Debugging your own code is part and parcel of learning how to write programs. – PaulMcKenzie Jun 30 '21 at 03:58
  • @PaulMcKenzie I just asked for a simple thing: the error in my code, because I wasn't able to figure it out myself. If you figure it out, please report it to me, because even with the debugger, I am not getting hint what's wrong. – newprogrammer Jun 30 '21 at 05:21
  • I have returned your post to the version which got a meaningful and relevant answer, in order to avoid turning this otherwise interesting post into a (not appreciated) "moving target" question. Please understand that most users here will be more helpfully minded if you recognise the effort people have already put into answering your post. Please create a new question to discuss your new problem. – Yunnosch Jun 30 '21 at 06:58
  • Also, I pointed out to you that you should start with a smaller array, and carefully follow what is being done, instead of starting out with 8 values. And last but not least, [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – PaulMcKenzie Jun 30 '21 at 07:57
  • @newprogrammer -- No one is bullying you. The issue is that you have to put in the effort to identify where the problem is. If you take a look at your post and all of your comments, nowhere did you pinpoint where the issue was. You could have said, "the finalArray is doing weird things to the original array", and that would have been good. Fixing the issue is a different story, as a new programmer may not be able to do this, but identifying where the problem is -- that is the least you should be able to do – PaulMcKenzie Jun 30 '21 at 08:16

1 Answers1

1

Merge merges into the finalArray, which has nothing to do with arr1. Once Merge returns, finalArray ceases to exist (leaking memory), and arr1 remains untouched.

Before return, copy finalArray back to arr1, and delete[] it.

user58697
  • 7,808
  • 1
  • 14
  • 28
  • I tried to edit my code, here's the new code:https://ide.codingblocks.com/s/581287 , but it is printing garbage values, please I request you to have a look at the code again and point out any error if it is still there. – newprogrammer Jun 30 '21 at 03:20
  • Hi newprogrammer. Please ask a new question concerning the problems you have after fixing the main problem in the code shown here. – Yunnosch Jun 30 '21 at 05:53
  • Hi newprogrammer, you might want to extend the interface of `Merge()` to allow selecting where the result should go. – Yunnosch Jun 30 '21 at 05:56
  • @Yunnosch The code that you are seeing in the problem description is the latest one. I could not understand what you mean by extending the interface of Merge() to allow selecting.. , can you please explain? – newprogrammer Jun 30 '21 at 06:50
  • What I mean is to NOT edit a given solution into the question and start discussing new problem you encounter with the new code. Please understand that the question you initially asked is considered answered now. Please return to that version of the question, consider this an answer to it (maybe accept it....) and then ask a new separate question on the new problem you have with the new code. Never mind my interface proposal. Just go to https://stackoverflow.com/questions/ask Your question post here should be returned to the version which was answered. It is otherwise seen as "moving target!". – Yunnosch Jun 30 '21 at 06:56