Sample Code Practice Problem


Forum Post 0 Answers Sample Code Practice Problem

Having a bit of trouble identifying why this code is throwing an out of bounds error on line 16. Not entirely sure how to fix it. I think I am overlooking something.

public class sampleCode {

public static void main( String[] moe ) {
int[] larry = new int[moe.length];
for( int i=0; i < moe.length; i++ ) {
larry[i] = Integer.parseInt( moe[i] );
}

int[] curly = null;
if( larry.length <= 10 ) {
curly = path1( larry );
} else
curly = path2( larry );

// PRINT RESULTS
System.out.println( curly[0]+", "+curly[1] );
}

public static int[] path1( int[] foo ) {
for( int i=0; i<foo.length; i++ ) {
for(int j=0; j<foo.length-1; j++) {
if( foo[j] > foo[j+1] ) {
int bar = foo[j];
foo[j] = foo[j+1];
foo[j+1] = bar;
}
}
}
return foo;
}

public static int[] path2( int[] foo ) {
int[] z = null;
if( foo.length > 1 ) {
int bar = foo.length / 2;
int[] a = new int[bar];
int[] b = new int[foo.length - bar];
for( int x=0; x<foo.length; x++ ) {
if( x<bar ) a[x] = foo[x];
else b[x-bar] = foo[x];
}
z = path2b( path2( a ), path2( b ) );
} else {
z = foo;
}
return z;
}

protected static int[] path2b( int[] foo, int[] bar ) {
int i=0;
int j=0;
int x=0;
int[] z = new int[foo.length+bar.length];
while( i<foo.length || j<bar.length ) {
if( i < foo.length && j == bar.length ) {
z[x] = foo[i++];
} else
if( j < bar.length && i == foo.length ) {
z[x] = bar[j++];
} else
if( foo[i] < bar[j] ) {
z[x] = bar[j++];
} else {
z[x] = foo[i++];
}
x++;
}
return z;
}
}

- elisefstorey October 12, 2015 | Flag |






Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More