is there a reason why my merge sort does not work for array length 10How does the Java 'for each' loop work?Why does Java have transient fields?Java & Merge SortWhy is it faster to process a sorted array than an unsorted array?Why does this code using random strings print “hello world”?merge sort not working when copying the result of merge operation directly to auxiliary arrayMerge Sort : need of copying elements from temporary arrayhow to make bottom up merge sort workImplementing Merge SortMergesort algorithm implementation
What's the metal clinking sound at the end of credits in Avengers: Endgame?
Any examples of headwear for races with animal ears?
Did Henry V’s archers at Agincourt fight with no pants / breeches on because of dysentery?
Why does processed meat contain preservatives, while canned fish needs not?
Build a trail cart
Does jamais mean always or never in this context?
How deep to place a deadman anchor for a slackline?
TikZ how to make supply and demand arrows for nodes?
Unexpected email from Yorkshire Bank
Historically, were women trained for obligatory wars? Or did they serve some other military function?
Examples of non trivial equivalence relations , I mean equivalence relations without the expression " same ... as" in their definition?
Pawn Sacrifice Justification
What word means to make something obsolete?
Given what happens in Endgame, why doesn't Dormammu come back to attack the universe?
Lock in SQL Server and Oracle
Toggle Overlays shortcut?
Confused by notation of atomic number Z and mass number A on periodic table of elements
What is the strongest case that can be made in favour of the UK regaining some control over fishing policy after Brexit?
Colliding particles and Activation energy
How can I get precisely a certain cubic cm by changing the following factors?
Phrase for the opposite of "foolproof"
In gnome-terminal only 2 out of 3 zoom keys work
How to creep the reader out with what seems like a normal person?
Is it possible to Ready a spell to be cast just before the start of your next turn by having the trigger be an ally's attack?
is there a reason why my merge sort does not work for array length 10
How does the Java 'for each' loop work?Why does Java have transient fields?Java & Merge SortWhy is it faster to process a sorted array than an unsorted array?Why does this code using random strings print “hello world”?merge sort not working when copying the result of merge operation directly to auxiliary arrayMerge Sort : need of copying elements from temporary arrayhow to make bottom up merge sort workImplementing Merge SortMergesort algorithm implementation
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am setting up merge sort to sort my array. The goal is to sort an array with any length.
I have tried looking at the mergesort function, but i do not see anything wrong with it. the sort works for some array length be it odd or even but for array length such as length of 10, i get an over bound exception.
import java.util.Arrays;
class MergeSort
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
java mergesort
add a comment |
I am setting up merge sort to sort my array. The goal is to sort an array with any length.
I have tried looking at the mergesort function, but i do not see anything wrong with it. the sort works for some array length be it odd or even but for array length such as length of 10, i get an over bound exception.
import java.util.Arrays;
class MergeSort
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
java mergesort
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55
add a comment |
I am setting up merge sort to sort my array. The goal is to sort an array with any length.
I have tried looking at the mergesort function, but i do not see anything wrong with it. the sort works for some array length be it odd or even but for array length such as length of 10, i get an over bound exception.
import java.util.Arrays;
class MergeSort
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
java mergesort
I am setting up merge sort to sort my array. The goal is to sort an array with any length.
I have tried looking at the mergesort function, but i do not see anything wrong with it. the sort works for some array length be it odd or even but for array length such as length of 10, i get an over bound exception.
import java.util.Arrays;
class MergeSort
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
java mergesort
java mergesort
asked Mar 22 at 19:18
chrisuyechrisuye
11
11
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55
add a comment |
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55
add a comment |
2 Answers
2
active
oldest
votes
Your mid calculation is incorrect. You are sometimes setting it outside the range of the area.
This below change fixes the algorithm by preventing mid from going out of bounds, similar to how you did with preventing to from going out of bounds.
Change int mid = i + m - 1;
to int mid = Math.min(i + m - 1, A.length - 1);
Explanation: As mentioned in your comment, the slices of area you are examining are increasing in size. So here is how your array is sorted, and when the out of bounds error occurs, and why it did not occur on sizes that are powers of 2:
[ -9, 5, 7, 3, -4, 2, 8, 8, 10, 11 ] Array size
First pass: [] [] [] [] [] [] [] [] [] [] 1
Second: [ ] [ ] [ ] [ ] [ ] 2
Third: [ ] [ ] [ ERROR] 4
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
add a comment |
Here is your fix:
Added an if statement for your mid not to cross the array bound
if(mid<high)
merge(A, temp, from, mid, to);
Complete code:
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
//System.out.println("temp Array : " + Arrays.toString(temp));
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
if(mid<high)
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306470%2fis-there-a-reason-why-my-merge-sort-does-not-work-for-array-length-10%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your mid calculation is incorrect. You are sometimes setting it outside the range of the area.
This below change fixes the algorithm by preventing mid from going out of bounds, similar to how you did with preventing to from going out of bounds.
Change int mid = i + m - 1;
to int mid = Math.min(i + m - 1, A.length - 1);
Explanation: As mentioned in your comment, the slices of area you are examining are increasing in size. So here is how your array is sorted, and when the out of bounds error occurs, and why it did not occur on sizes that are powers of 2:
[ -9, 5, 7, 3, -4, 2, 8, 8, 10, 11 ] Array size
First pass: [] [] [] [] [] [] [] [] [] [] 1
Second: [ ] [ ] [ ] [ ] [ ] 2
Third: [ ] [ ] [ ERROR] 4
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
add a comment |
Your mid calculation is incorrect. You are sometimes setting it outside the range of the area.
This below change fixes the algorithm by preventing mid from going out of bounds, similar to how you did with preventing to from going out of bounds.
Change int mid = i + m - 1;
to int mid = Math.min(i + m - 1, A.length - 1);
Explanation: As mentioned in your comment, the slices of area you are examining are increasing in size. So here is how your array is sorted, and when the out of bounds error occurs, and why it did not occur on sizes that are powers of 2:
[ -9, 5, 7, 3, -4, 2, 8, 8, 10, 11 ] Array size
First pass: [] [] [] [] [] [] [] [] [] [] 1
Second: [ ] [ ] [ ] [ ] [ ] 2
Third: [ ] [ ] [ ERROR] 4
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
add a comment |
Your mid calculation is incorrect. You are sometimes setting it outside the range of the area.
This below change fixes the algorithm by preventing mid from going out of bounds, similar to how you did with preventing to from going out of bounds.
Change int mid = i + m - 1;
to int mid = Math.min(i + m - 1, A.length - 1);
Explanation: As mentioned in your comment, the slices of area you are examining are increasing in size. So here is how your array is sorted, and when the out of bounds error occurs, and why it did not occur on sizes that are powers of 2:
[ -9, 5, 7, 3, -4, 2, 8, 8, 10, 11 ] Array size
First pass: [] [] [] [] [] [] [] [] [] [] 1
Second: [ ] [ ] [ ] [ ] [ ] 2
Third: [ ] [ ] [ ERROR] 4
Your mid calculation is incorrect. You are sometimes setting it outside the range of the area.
This below change fixes the algorithm by preventing mid from going out of bounds, similar to how you did with preventing to from going out of bounds.
Change int mid = i + m - 1;
to int mid = Math.min(i + m - 1, A.length - 1);
Explanation: As mentioned in your comment, the slices of area you are examining are increasing in size. So here is how your array is sorted, and when the out of bounds error occurs, and why it did not occur on sizes that are powers of 2:
[ -9, 5, 7, 3, -4, 2, 8, 8, 10, 11 ] Array size
First pass: [] [] [] [] [] [] [] [] [] [] 1
Second: [ ] [ ] [ ] [ ] [ ] 2
Third: [ ] [ ] [ ERROR] 4
edited Mar 22 at 20:11
answered Mar 22 at 19:35
Daryll ChandlerDaryll Chandler
1487
1487
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
add a comment |
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Thank you, It fixed the problem. if you have any additional input I will gladly accept. and I will work towards finding any other problem I find.
– chrisuye
Mar 22 at 20:11
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
Updated my answer. I believe the approach is actually the best way to solve the problem and cap the number. The alternatives involve rewriting more code and in some cases slower anyways.
– Daryll Chandler
Mar 22 at 20:14
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
This approach does not reduce the number of calls made to the merge function, for a 10 number array the calls made are 11. Where as if you add the if conditional statement the number of calls gets reduces to 9. Check below solution for the same. Please do correct me if I am wrong
– VSB
Mar 22 at 20:20
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
You're correct, this implementation of merge sort could be optimized. A break or conditional would stop it from unnecessarily re-sorting that section.
– Daryll Chandler
Mar 22 at 20:37
add a comment |
Here is your fix:
Added an if statement for your mid not to cross the array bound
if(mid<high)
merge(A, temp, from, mid, to);
Complete code:
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
//System.out.println("temp Array : " + Arrays.toString(temp));
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
if(mid<high)
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
add a comment |
Here is your fix:
Added an if statement for your mid not to cross the array bound
if(mid<high)
merge(A, temp, from, mid, to);
Complete code:
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
//System.out.println("temp Array : " + Arrays.toString(temp));
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
if(mid<high)
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
add a comment |
Here is your fix:
Added an if statement for your mid not to cross the array bound
if(mid<high)
merge(A, temp, from, mid, to);
Complete code:
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
//System.out.println("temp Array : " + Arrays.toString(temp));
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
if(mid<high)
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
Here is your fix:
Added an if statement for your mid not to cross the array bound
if(mid<high)
merge(A, temp, from, mid, to);
Complete code:
// Merge two sorted sub-arrays A[from .. mid] and A[mid + 1 .. to]
public static void merge(int[] A, int[] temp, int from, int mid, int to)
int k = from, i = from, j = mid + 1;
// loop till there are elements in the left and right runs
while (i <= mid && j <= to)
if (A[i] < A[j])
temp[k++] = A[i++];
else
temp[k++] = A[j++];
// Copy remaining elements
while (i <= mid)
temp[k++] = A[i++];
// Don't need to copy second half
// copy back to the original array to reflect sorted order
for (i = from; i <= to; i++)
A[i] = temp[i];
// Iteratively sort array A[low..high] using temporary array
public static void mergesort(int[] A)
int low = 0;
int high = A.length - 1;
// sort array A[] using temporary array temp
int[] temp = Arrays.copyOf(A, A.length);
//System.out.println("temp Array : " + Arrays.toString(temp));
// divide the array into blocks of size m
// m = [1, 2, 4, 8, 16...]
for (int m = 1; m <= high - low; m = 2*m)
// for m = 1, i = 0, 2, 4, 6, 8...
// for m = 2, i = 0, 4, 8, 12...
// for m = 4, i = 0, 8, 16...
// ...
for (int i = low; i < high; i += 2*m)
int from = i;
int mid = i + m - 1;
int to = Integer.min(i + 2 * m - 1, high);
if(mid<high)
merge(A, temp, from, mid, to);
// Iterative Implementation of Mergesort algorithm
public static void main(String[] args)
int[] A = 5, 7, -9, 3, -4, 2, 8, 8, 10, 11 ;
System.out.println("Original Array : " + Arrays.toString(A));
mergesort(A);
System.out.println("Modified Array : " + Arrays.toString(A));
answered Mar 22 at 20:12
VSBVSB
25229
25229
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55306470%2fis-there-a-reason-why-my-merge-sort-does-not-work-for-array-length-10%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It is caused by A[i++] at line 19
– Kars
Mar 22 at 19:27
Thank you for the response, I have already found that problem. how to I fix it tho.
– chrisuye
Mar 22 at 19:46
This looks like a perfect time to use the debugger
– Joakim Danielson
Mar 22 at 19:55