Sort elements of an array in ascending order (java) -
im trying sort array in ascending order. reason performs loop once. why doesn't keep going until sorted? help
public class sudoku { public static void main(string[] args) { int[] = { 1, 4, 3, 5, 2 }; system.out.println(arrays.tostring(sortarray(a))); } public static int[] sortarray(int[] nonsortedarray) { int[] sortedarray = new int[nonsortedarray.length]; int temp; (int = 0; < nonsortedarray.length - 1; i++) { if (nonsortedarray[i] > nonsortedarray[i + 1]) { temp = nonsortedarray[i]; nonsortedarray[i] = nonsortedarray[i + 1]; nonsortedarray[i + 1] = temp; sortedarray = nonsortedarray; } } return sortedarray; } }
try using existing java api, after modifying code
public static void main(string[] args) { int[] = { 1, 4, 3, 5, 2 }; arrays.sort(a); system.out.println(arrays.tostring(a)); }
or
public static int[] sortarray(int[] nonsortedarray) { int[] sortedarray = new int[nonsortedarray.length]; int temp; (int j = 0; j < nonsortedarray.length - 1; j++) {// added loop, think logic why have add make work (int = 0; < nonsortedarray.length - 1; i++) { if (nonsortedarray[i] > nonsortedarray[i + 1]) { temp = nonsortedarray[i]; nonsortedarray[i] = nonsortedarray[i + 1]; nonsortedarray[i + 1] = temp; sortedarray = nonsortedarray; } } } return sortedarray; }
output:[1, 2, 3, 4, 5] or //making use of j
public static int[] sortarray(int[] nonsortedarray) { int[] sortedarray = new int[nonsortedarray.length]; int temp; (int = 0; <= nonsortedarray.length; i++) { (int j = i+1; j < nonsortedarray.length; j++) { if (nonsortedarray[i] > nonsortedarray[j]) { temp = nonsortedarray[i]; nonsortedarray[i] = nonsortedarray[j]; nonsortedarray[j] = temp; sortedarray = nonsortedarray; } } } return sortedarray; }
http://docs.oracle.com/javase/7/docs/api/java/util/arrays.html#sort(int[])
public static void sort(int[] a) sorts specified array ascending numerical order. implementation note: sorting algorithm dual-pivot quicksort vladimir yaroslavskiy, jon bentley, , joshua bloch. algorithm offers o(n log(n)) performance on many data sets cause other quicksorts degrade quadratic performance, , typically faster traditional (one-pivot) quicksort implementations. parameters: - array sorted
Comments
Post a Comment