I've been tasked with creating a method that will print all the indices where value x is found in a sorted array.
I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case. Since the array that will be passed into the method will be sorted, I'm assuming that I can take advantage of using a Binary Search since this will be O(log n). However, this only works if the array has unique values. Since the Binary Search will finish after the first "find" of a particular value. I was thinking of doing a Binary Search for finding x in the sorted array, and then checking all values before and after this index, but then if the array contained all x values, it doesn't seem like it would be that much better.
I guess what I'm asking is, is there a better way to find all the indices for a particular value in a sorted array that is better than O(n)?
public void PrintIndicesForValue42(int[] sortedArrayOfInts)
{
// search through the sortedArrayOfInts
// print all indices where we find the number 42.
}
Ex: sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"
Alternatevely, instead of counting the number of occurances, you can put their indices in a arraylist and put that in the map instead of the count.
heh, i guess this will have to be posted.
A Hashmap might work, if you're not required to use a binary search.
Create a HashMap where the
Key
is the value itself, and then value is an array of indices where that value is in the array. Loop through your array, updating each array in the HashMap for each value.Lookup time for the indices for each value will be ~ O(1), and creating the map itself will be ~ O(n).
Below is the java code which returns the range for which the search-key is spread in the given sorted array:
This would run in O(log(n) + #occurrences) Read and understand the code. It's simple enough.