0

Having a method and arr being already sorted...

public int search(ArrayList<Integer> arr, int numberToBeSearched) {
    //Code here
    return //insertion point
}

Let arr be{1, 4, 7} and numberToBeSearched 2. return would be 1 because it would be between 1 and 4 in order to maintain the order.

How would you guys get the insertion point of numberToBeSearched inside arr without using Collections.binarySearch?

The insertion point is the index position where the number would need to be inserted in the array-list so as to maintain the sort order.

ismael oliva
  • 97
  • 1
  • 3
  • 11

1 Answers1

0
        public int search(ArrayList<Integer> arr, int numberToBeSearched) {
            int i=0;
            for (i = 0; i < size(); i++) {
                // if the element you are looking at is smaller than numberToBeSearched, 
                // go to the next element
                if (arr.get(i) < numberToBeSearched) continue;
                // if the element equals numberToBeSearched, return, because we don't duplicates
                if (arr.get(i) == numberToBeSearched) return -1;
                // otherwise, we have found the location of numberToBeSearched
                return i;
            }
            // we looked through all of the elements, and they were all
            // smaller than numberToBeSearched, so the index is  end of the list
            return i;
        }
Nivethi Mathan
  • 105
  • 1
  • 8