Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i find the positions to the three lowest integers in an array?
    primarykey
    data
    text
    <p>I how can I find the positions of the three lowest integers in an array? I've tried to reverse it, but when I add a third number, it all goes to hell :p Does anybody manage to pull this one off and help me? :)</p> <p>EDIT: It would be nice to do it without changing or sorting the original array a.</p> <pre><code>public static int[] lowerThree(int[] a) { int n = a.length; if (n &lt; 2) throw new java.util.NoSuchElementException("a.length(" + n + ") &lt; 2!"); int m = 0; // position for biggest int nm = 1; // position for second biggest if (a[1] &gt; a[0]) { m = 1; nm = 0; } int biggest = a[m]; // biggest value int secondbiggest = a[nm]; // second biggest for (int i = 2; i &lt; n; i++) { if (a[i] &gt; secondbiggest) { if (a[i] &gt; biggest) { nm = m; secondbiggest = biggest; m = i; biggest = a[m]; } else { nm = i; secondbiggest = a[nm]; } } } // for return new int[] {m,nm}; } </code></pre> <p>EDIT: I've tried something here but it still doesn't work. I get wrong output + duplicates...</p> <pre><code> public static int[] lowerthree(int[] a) { int n= a.length; if(n &lt; 3) throw new IllegalArgumentException("wrong"); int m = 0; int nm = 1; int nnm= 2; int smallest = a[m]; // int secondsmallest = a[nm]; / int thirdsmallest= a[nnm]; for(int i= 0; i&lt; lengde; i++) { if(a[i]&lt; smallest) { if(smalles&lt; secondsmallest) { if(secondsmallest&lt; thirdsmallest) { nnm= nm; thirdsmallest= secondsmallest; } nm= m; secondsmallest= smallest; } m= i; smallest= a[m]; } else if(a[i] &lt; secondsmallest) { if(secondsmallest&lt; thirdsmallest) { nnm= nm; thirdsmallest= secondsmallest; } nm= i; secondsmallest= a[nm]; } else if(a[i]&lt; thirdsmallest) { nnm= i; thirdsmallest= a[nnm]; } } return new int[] {m, nm, nnm}; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload