java - Running several iterations in a while loop -
i trying solve problem of finding smallest , second smallest element in array.
i thinking of putting 2 pointers on 0th index of array. both pointers move left right traversing entire array. first pointer ptr1 determines min element while second pointer intends determine second min element. first pointer works ok second pointer doesn't traverse. while loop exits after 1 iteration of second pointer.
is possible have n pointers in while loop & make them traverse left right turn turn?
or doing wrong.
below code
int arr[] = {12,13,1,10,34,1}; int ptr1 = 0; int ptr2 =0; int min = integer.max_value; int minsec = integer.max_value; int arrlen=arr.length-1; while(ptr1<arrlen && ptr2<arrlen){ if(arr[ptr1]<min){ // if works great finds min element min=arr[ptr1]; ptr1++; }else{ ptr1++; } //flow enters once & exits while loop if(ptr1==arrlen && arr[ptr2]<minsec && arr[ptr2]>min){ minsec=arr[ptr2]; ptr2++; }else if(ptr1==arrlen){ ptr2++; } } system.out.println("min: " + min + " second min: "+ minsec)
output: min: 1 second min: 12
the correct output should min: 1 second min: 10
i able solve problem approach, code below. need know while loop approach.
for (int = 0; <= arrlen ; ++) { /* if current element smaller first update both first , second */ if (arr[i] < min) { minsec = min; min = arr[i]; } /* if arr[i] in between first , second update second */ else if (arr[i] < minsec && arr[i] != min) minsec = arr[i]; }
because ptr2 value 0 until loop reach end
if(ptr1==arrlen && arr[ptr2]<minsec && arr[ptr2]>min){ minsec=arr[ptr2]; ptr2++; }
and enter if condition ptr1==arrlen
select minsec
value minsec=arr[ptr2]
. no point of putting condition here.
so second if condition
if(arr[ptr2]<minsec && arr[ptr2]>min){ minsec=arr[ptr2]; ptr2++; }else{ ptr2++; }
Comments
Post a Comment