Sorting 2 sets of scores with array in java -
i wrote following code rank 2 sets of scores:
public class scoreranking { public static void main(string[] args) { int[] score1 = { 9, 3, 6, 19 }; int[] score2 = { 3, 3, 3, 3, 3, 5, 1 }; int[] rank1 = sortscores(score1); int[] rank2 = sortscores(score2); (int = 0; < rank1.length; i++) { system.out.println((i + 1) + ": " + rank1[i]); } system.out.println("_________\n"); (int j = 0; j < rank2.length; j++) { system.out.println((j + 1) + ": " + rank2[j]); } } static int[] sortscores(int[] sort) { (int = 0; < sort.length - 1; i++) { if (sort[i] < sort[i + 1]) { continue; } else { int temp = sort[i]; sort[i] = sort[i + 1]; sort[i + 1] = temp; } } return sort; } }
the first set ordered second isn't. played around brackets, tried different order (int score 1... int rank1... int score2... int rank2... / int score2..., int rank2... int score1... int rank1...) - score2 "ignored". can please tell me why?
i made cold debug , think you're problem sortscores method. if i'm not wrong rank2 array sorted {3, 3, 3, 3, 3, 1, 5}.
the main problem facing algorithm change , i+1 elements, happen when i+2 elements in lower element, there method fails doesn't job correctly.
if want develop sorting algorithm recommend first make sort array 5 or 4 elements in paper , them try understand doing, them write steps in pseudo code , translate java longer guaranteed more satisfactory, if want sort array write them should check sorting algorithms on wikipedia , take special on insertion sort easy understand , doesn't have complexity.
at last, if want used java libraries save time , code them should check array class sort(int[] a) method.
i hope answers understand better world.
bye, greetings venezuela
pd. insertion sort algorithm one:
public static void insertionsort (int[] array) { (int i=1; < array.length; i++) { int aux = array[i]; int j; (j=i-1; j >= 0 && array[j] > aux; j--){ array[j+1] = array[j]; } array[j+1] = aux; } }
Comments
Post a Comment