get list of unused numbers from an unsorted array in java -
i need smallest unused number unsorted array. not sort array because test program, in actual program, taking values array of objects.
so while trying smallest unused number, managed list of unused numbers. perfect first random numbers wrote in program, second time, output wrong.
this code tried
class smallestunusednumbertest { public static void main(string args[]) { int[] testarray = {1, 5, 7, 11, 4, 8}; int largest = 1; int i; for(i = 0; < testarray.length; i++) { if(testarray[i] > largest) { largest = testarray[i]; } } for(i = 1; < largest; i++) { for(int j = 0; j < testarray.length; j++) { if(i == testarray[j]) { i++; } } system.out.println(i); } } }
and output is
2 3 5 6 9 10
i 5, there in array. have used for
loop largest number array. then, not able figure out correct logic.
what should correct unused numbers array? need output in ascending order.
there problem logic of algorithm: increment i
inside inner loop when find match, continue loop. therefore, when find 4
after 5
, increment i
4
5
, never go beginning of array see if of earlier elements 5
.
to fix this, define boolean
variable inside outer loop, set false
initially, , set true
in inner loop when find i == testarray[j]
; break out of loop when find match.
check boolean variable after inner loop. if true
, number there, should not print anything. otherwise, print number.
Comments
Post a Comment