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

Java program for detecting server login prompt?
Keep getting java.lang.NoClassDefFoundError in Spring
How to bind to more than 1 ReactFX observable?
How to use custom converters with #DataMongoTest?
Where did the lib project go for google play services?
Get only latest posts of Facebook using RestFB
printf is giving me the wrong output
How to get the path name outside the loop?
Spring Data Mongo + Lazy Load + REST Jackson
Multithreading Animation on Javafx
JHipster with Liquibase in production
java bankaccount program issue with a method
I tried looking for solutions for “No mapping found for HTTP request with URI [/DemoApp/index] in DispatcherServlet with name 'servlet'”
Jubula on linux(Centos 7)
Error 400 because of accents on a JSON field
Regular Expression backtracks until overflow in Java

Categories

HOME
jdo
netsuite
netbeans
layout
objectgears
sqlite3
c#-2.0
webpack-2
blueprintjs
datastax-java-driver
in-app-purchase
directx
esper
iggrid
u-sql
windows-azure-storage
orchardcms
netflix
lombok
workload-scheduler
libtiff
openrefine
propel
nhibernate-envers
google-pagespeed
cx-freeze
arabic
graphicsmagick
android-widget
pepper
phpfox
maxmind
strncpy
wtx
atlassian-crucible
subdomains
frame
winrt-xaml-toolkit
commit
accelerate-framework
simplexml
mixture-model
greenrobot-eventbus
avro4s
eigenvalue
spring-security-kerberos
password-encryption
heightmap
reactive-cocoa-5
youcompleteme
python-c-api
clean-architecture
datastax-startup
mu
kbuild
capacity
jspdf-autotable
bind9
cubes
removechild
ctest
contact-list
lttng
prettytensor
itextpdf
sdhc
metaclass
kcachegrind
method-parameters
processmodel
census
proj4js
python-green
block-device
operator-precedence
jscript.net
rdl
flask-cors
yorick
doskey
valuechangelistener
hippomocks
multiprocessor
farseer
xamlparseexception
html-editor
cassini-dev
venn-diagram
cascalog
viewswitcher
ticoredatasync
fireworks
gnustep
yetanotherforum
propagation
iphone-web-app
subviews
infrastructure
preference
ext3
nerddinner
dbisam
windows-live-messenger

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App