java


Can't figure out what is wrong with my merge sort code


I went over it multiple times and I am not sure what I am doing wrong.
he logic seems OK but it is printing out the first number only. I left out the main method:
public class MergeSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] bob = {4,7,99,8,12,6};
Mergesort(bob);
for(int i=0; i< bob.length; i++){
System.out.print(bob[i]+",");
}
}
public static int[] Mergesort(int[] bob){
int length = bob.length;
int mid = bob.length/2;
if(length <= 1){
return bob;
}
int[] left = new int[mid];
int[] right = new int[length-left.length];
for(int i=0; i< mid; i++){
left[i]=bob[i];
}
for(int j=mid; j< length; j++){
right[j-mid]=bob[j];
}
Mergesort(left);
Mergesort(right);
merge(left,right, bob);
return bob;
}
//this is merge method
public static int[] merge(int[] left, int[] right, int[] bob){
int l= left.length;
int r = right.length;
int i=0, j=0,k=0;
while(i<l && j<r){
if(left[i]<=right[j]){
bob[k] = left[i];
i++;
}
else
{
bob[k] = right[j];
j++;
}
k++;
}
while(i<l){
bob[k] = left[i];
i++;
k++;
}
while(j<r){
bob[k] = bob[j];
j++;
k++;
}
return bob;
}
}
Rather than just tell you the answer, I'm going to show you how to quickly figure it out via test/debug. You know, "teach a man to fish" and all that (source).
So, let's test your merge method. I've modified the main method to only merge two sorted arrays {1, 3, 5} and {2, 4, 6}. We know that the output should be {1, 2, 3, 4, 5, 6}.
At the same time, let's debug as well. The most primitive way to debug is known as "printf debugging," meaning we just put lots of logging statements in the code so that we can see what the internal state is at every step. I've added logging wherever your merge output array is modified. The goal is to observe the moment it is modified in an incorrect/unexpected way.
Here's the code with these two modifications:
public class MergeSort {
public static void main(String[] args) {
int[] left = {1, 3, 5};
int[] right = {2, 4, 6};
int[] merged = {0, 0, 0, 0, 0, 0};
merge(left, right, merged);
}
public static int[] merge(int[] left, int[] right, int[] bob) {
System.out.print("Before merge: ");
System.out.println(Arrays.toString(bob));
int l = left.length;
int r = right.length;
int i = 0, j = 0, k = 0;
while (i < l && j < r) {
if (left[i] <= right[j]) {
bob[k] = left[i];
System.out.print("Merge step 1: ");
System.out.println(Arrays.toString(bob));
i++;
} else {
bob[k] = right[j];
System.out.print("Merge step 2: ");
System.out.println(Arrays.toString(bob));
j++;
}
k++;
}
while (i < l) {
bob[k] = left[i];
System.out.print("Merge step 3: ");
System.out.println(Arrays.toString(bob));
i++;
k++;
}
while (j < r) {
bob[k] = bob[j];
System.out.print("Merge step 4: ");
System.out.println(Arrays.toString(bob));
j++;
k++;
}
return bob;
}
}
And here is the output:
Before merge: [0, 0, 0, 0, 0, 0]
Merge step 1: [1, 0, 0, 0, 0, 0]
Merge step 2: [1, 2, 0, 0, 0, 0]
Merge step 1: [1, 2, 3, 0, 0, 0]
Merge step 2: [1, 2, 3, 4, 0, 0]
Merge step 1: [1, 2, 3, 4, 5, 0]
Merge step 4: [1, 2, 3, 4, 5, 3]
So, where is the problem in your code? Clearly in "merge step 4," or the line bob[k] = bob[j];. How cool is that? With a few simple print calls, we've located the exact line of your bug!
I believe your bug is in this line in merge():
bob[k] = bob[j];
It should be
bob[k] = right[j];
With this change I get this output:
4,6,7,8,12,99,

Related Links

Ant build successful, yet Eclipse shows errors. (new to Eclipse / Java)
How do i split user input in java - and convert into double?
How to read data from file to create objects?
How do I import a AIDE project into IntelliJ?
hibernate not working on Jboss
Jtoolbar isn't displaying
java.util.ServiceLoader.load() function is useless and only returns empty result
Arraylist remove method except out of bound
Can't Mock Stored procedure in JOOQ
Ways to create custom commands for a text based adventure game?
implicit cast char array to int array
JNI thread causing SIGSEGV Cypress fx2lp USB chip
Alternative to using Graphics2D Area?
Combining #Context and #RolesAllowed in a JAX-RS resource?
How to do upsert in Zookeeper/Curator?
Maven separate Building and packaging and Cucumber Integration tests

Categories

HOME
cakephp
osgi
blogger
view
platform-builder
q
sqlite-net-extensions
youtube-api-v3
icloud
blueprintjs
bs4
add
synchronization
cloudkit
dacpac
gnupg
izpack
handsontable
ghc
django-admin
invantive-sql
reactcsstransitiongroup
jqwidget
firefox-webextensions
devops
claims-based-identity
crystal-reports-2010
pepper
status
bootstrap-duallistbox
windows-error-reporting
xacml
compatibility
libuv
socialengine
stormpath
galsim
repo
uiswipegesturerecognizer
openoffice.org
wallpaper
normal-distribution
mapdb
sequential
hexo
mixture-model
dynamics-crm-2013
xenforo
android-fingerprint-api
bootstrapper
texmaker
turbogears
heightmap
outlook-api
acoustics
slick-3.0
jsch
flickr-api
komodoedit
python-c-api
tizen-native-app
integrity
setter
zendesk-app
hittest
minimization
google-cdn
root-framework
setuptools
gridpane
probability-density
dstu2-fhir
qpid
persist
moveit
blackberry-10
suffix-tree
independentsoft
spidermonkey
sframe
service-accounts
apache-commons-fileupload
system32
modalpopup
angularjs-ng-click
gui-test-framework
device-manager
websocket4net
eol
rebol3
rtmfp
balanced-payments
app42
oam
dataservice
interface-orientation
sharp-repository
eventlistener
gil
nsnetservice
google-email-migration
custom-backend
f#-powerpack
propagation
fluent-interface
sudzc
asp.net-mvc-areas
ncqrs
thunderbird-lightning
user-friendly
meego
webkit.net
eqatec
temporal-database
sustainable-pace
defensive-programming

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App