Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to search for a range of values using binary search?
    primarykey
    data
    text
    <p>I am trying to write a program that will take an <em>ArrayList</em> of sorted integers, and there will be a binary search method where you specify the range and the values that you want to be returned from the <em>ArrayList</em>.</p> <pre><code>import java.util.ArrayList; public class ArraySearch { ArrayList&lt;Integer&gt; myArrayList = new ArrayList&lt;Integer&gt;(); static ArrayList&lt;Integer&gt; range = new ArrayList&lt;Integer&gt;(); public static ArrayList&lt;Integer&gt; binarySearch(ArrayList&lt;Integer&gt; arrayList, int min, int max, int first, int last) throws NotFoundException { if(first &gt; last) { throw new NotFoundException("Elements not found."); } else { int middle = (first + last) /2; int mid_number = arrayList.get(middle); if(mid_number &gt;= min &amp;&amp; mid_number &lt;= max) { range.add(middle); } if(mid_number &lt;= min) { if(mid_number == min) { range.add(arrayList.get(middle)); return binarySearch(arrayList, min, max, first, middle-1); } return binarySearch(arrayList, min, max, first, middle-1); } else { if(mid_number == max) { range.add(arrayList.get(middle)); return binarySearch(arrayList, min, max, middle+1,last); } return binarySearch(arrayList, min, max, middle+1,last); } } } public static void main (String [] args) throws NotFoundException { ArrayList&lt;Integer&gt; a = new ArrayList&lt;Integer&gt;(); a.add(0); a.add(1); a.add(2); a.add(3); a.add(6); a.add(7); a.add(7); a.add(10); a.add(10); a.add(10); binarySearch(a, 3, 7, 0, 9); } </code></pre> <p>}</p> <p>Could I please get some help?<br> I have no idea what the base case condition should be that should return the <em>ArrayList</em> range. And I think I might have got the logic in the binary search method wrong.</p>
    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.
    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