unending loop in java -
i have here code search of deepest pit in array
i search deepest pit using formula
min(a[trip] - a[triq], a[trir] - a[triq]);
where trip
first point, triq
second , trir
third.
what dont not able see printing. or rather code has infinite loop.
int[] = {0, 1, 3, -2, 0, 1, 0, -3, 2, 3}; int length = a.length, depth = 0, x = 0, mind; int trip = 0, triq = 0, trir = 0; while(x < length){ while(x < length){ if(x + 1 == length) break; x++; if(a[trip] > a[x]){ while(a[trip] > a[x]){ if(x + 1 == length) break; x++; } triq = x; break; } else{ trip++; if(x + 1 == length) break; x++; continue; } } while(x < length){ if(x + 1 == length) break; x++; if(a[triq] < a[x]){ while(a[triq] < a[x]){ if(x + 1 == length) break; x++; } trir = x; break; } else{ triq++; if(x + 1 == length) break; x++; continue; } } mind = math.min(a[trip] - a[triq], a[trir] - a[triq]); if(depth < mind){ depth = mind; } if(x >= length) break; } if(depth == 0) system.out.println("-1"); else system.out.println(depth);
what wrong code?
i'm not quite sure existing algorithm doing, if i've understood intent you're trying find index in array min(a[i-1] - a[i], a[i+1] - a[i])
largest? can expressed more as:
int[] = { 0, 1, 3, -2, 0, 1, 0, -3, 2, 3 }; int best = 0; int bestindex = -1; (int = 1; < a.length - 1; ++i) { int depth = math.min(a[i - 1] - a[i], a[i + 1] - a[i]); if (depth > best) { best = depth; bestindex = i; } } if (bestindex == -1) system.out.println("not found"); else system.out.println("deepest pit @ index " + bestindex + " == " + best);
the output of is:
deepest pit @ index 7 == 3
Comments
Post a Comment