Click here to Skip to main content
15,179,246 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Here is the link of the code

What I have tried:

I have tried the approach given in the link.
Posted
Updated 30-May-21 13:24pm

Nope. I'm not following links to look at gawd knows how much code because you can't be bothered to extract just the relevant sections, paste it here, and tell us where in that fragment the error occurs.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
   
You're not splitting a 2-element list into two 1-element lists in mergeSort(). Run your code with just two values and print out the lists at head and nhead after splitting the lists and before recursively sorting them. Your printList() function will be handy for that.

The effect of that is infinite recursion. Your "segmentation error" is the result of a stack overflow. All sorts of other errors can be reported as a result of crashing the stack.

It looks like changing the initialization of the fast/slow pointers in findMid() will fix that:
C++
Node *slow_ptr = head;
Node *fast_ptr = slow_ptr->next; //***this is the fix

You might also want to add a test for a null head pointer before doing that, but it doesn't look like you'll ever call that function when the list is empty.

The idea is that you use the "mid pointer" not as the head of the right-side list, but rather as the tail of the left-size list. That fix effectively starts the fast pointer half a cycle sooner so that the slow pointer lags behind it's old position by one list entry. You'll always get two nonempty lists when there are at least two elements in the starting list.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900