Java Insertion Sort not sorting -
public static void main(string[] args) { movies2[] movies = new movies2[10]; movies[0] = new movies2("the muppets take manhattan", 2001, "columbia tristar"); movies[1] = new movies2("mulan special edition", 2004, "disney"); movies[2] = new movies2("shrek 2", 2004, "dreamworks"); movies[3] = new movies2("the incredibles", 2004, "pixar"); movies[4] = new movies2("nanny mcphee", 2006, "universal"); movies[5] = new movies2("the curse of were-rabbit", 2006, "aardman"); movies[6] = new movies2("ice age", 2002, "20th century fox"); movies[7] = new movies2("lilo & stitch", 2002, "disney"); movies[8] = new movies2("robots", 2005, "20th century fox"); movies[9] = new movies2("monsters inc.", 2001, "pixar"); printmovies(movies); sorttitle(movies, 1); printmovies(movies); //sortyear(movies, 2); //printmovies(movies); //sortstudio(movies, 1); //printmovies(movies); } public static void printmovies(movies2[] list) { for(int = 0; < list.length; i++) system.out.println(list[i]); } public static movies2[] sorttitle(movies2[] source, int direction) { movies2[] dest = new movies2[ source.length ]; if(direction == 1) { system.out.println("sort title - ascending"); ( int = 0 ; < source.length ; i++ ) { movies2 next = source[i]; int insertindex = 0; int k = i; while ( k > 0 && insertindex == 0 ) { if ( next.gettitle().compareto(dest[k-1].gettitle()) > 0 ) { insertindex = k; } else { dest[ k ] = dest[ k - 1 ]; } k--; } dest[ insertindex ] = next; } } else if( direction == 2) { system.out.println("sort title - descending"); ( int = 0 ; < source.length ; i++ ) { movies2 next = source[ ]; int insertindex = 0; int k = i; while ( k > 0 && insertindex == 0 ) { if ( next.gettitle().compareto(dest[k-1].gettitle()) < 0 ) { insertindex = k; } else { dest[ k ] = dest[ k + 1 ]; } k--; } dest[ insertindex ] = next; } } else { dest = source; } return dest;
} have code array of movies. in movies class there getter methods parameters. when try run code number being 2, descending choice, gives me null error. when try 1 ascending, doesn't sort it.
the problem here
if (next.gettitle().compareto(dest[k - 1].gettitle()) > 0) {
may next.gettitle()
null
. title not set properly.
try simple method sort array:
public static void sort(movies2[] numbers, boolean ascending) { movies2 tempvar = null; (int = 0; < numbers.length; i++) { (int j = 1; j < numbers.length - i; j++) { int diff = numbers[j - 1].gettitle().compareto(numbers[j].gettitle()); if ((ascending && diff > 0) || (!ascending && diff < 0)) { tempvar = numbers[j - 1]; numbers[j - 1] = numbers[j]; numbers[j] = tempvar; } } } }
Comments
Post a Comment