java - Finding minimum integer in ArrayList without collections -
i'm trying find smallest integer in arraylist
using 2 simple for
loops. tried 1 for
loop, wasn't updating correctly. haven't learned collections
yet, should done without using collections
code.
this have:
public static void printinorder(arraylist<integer> data){ int minindex = 0 ; for(int = 0; < data.size(); i++){ minindex = i; for(int j = + 1; j < data.size() - 1; j++){ if(data.get(j) < data.get(minindex)){ minindex = j;} } system.out.println(data.get(minindex) + " "); } }//printinorder
my minimum seems last value in list, tried printing data.get(minindex)
in first for
loop see happens, , seems update different values, , finally, last value. have no idea why happening.
this it's printing example:
original list: [47, 19, 46, 42, 15, 26, 36, 27, 13, 15, 1, 40, 34, 14, 6, 34, 28, 12, 15, 13] print minimum: 1 1 1 1 1 1 1 1 1 1 1 6 6 6 6 12 12 12 15 13
you can quick solution if want avoid using collections.
public static void printinorder(arraylist<integer> data){ integer[] array = (integer[]) data.toarray(); arrays.sort(array); system.out.println(array[0]); }
the smallest integer @ index 0 in case.
or, if want go through whole arraylist using loop, i'd suggest store actual value in variable instead of index. doing so, get:
public static void printinorder(arraylist<integer> data){ int mininteger = data.get(0); for(int = 1; < data.size(); i++){ if(data.get(i) < mininteger) mininteger= data.get(i); } system.out.println(mininteger); }