0

I want to find the index of the start up letter and then show the index of that item in array or array list in java. Example: I have:

String[] arr={"apple","at","book","bad","car","cat"};

when I input a: then i will get index =0, b: i will get index=2, c: i will get index=4

Because my array item is over 20,000 , so using linear Search is too slow. and my list is unsorted, so i can't use Binary Search also. I want to get index of the item like the example above, what can i solve with this?

Ruby Man
  • 43
  • 8

2 Answers2

0

If you want to get all the indexes of words starting with a certain letter then try this one:

While adding the Words to your Array/list (that will hold all your words) you could also add it to a map that will hold all indexes for every first letters.

 Map<String, ArrayList<Integer>> myMap = new HashMap<String, ArrayList<Integer>>();

 public void yourmethod() {
    //adding all your words to an Array/arraylist goes here. (arr[] in this case)

    string firstLetter = yourword.substring(0,1);

    if(myMap.constainsKey(firstLetter)) {
       myMap.get(letter).add(yourword);
    } else {
         myMap.put(firstLetter, yourword);
    }
 }
Henrik
  • 1,797
  • 4
  • 22
  • 46
  • So, if the user continue type the next letter, example: ap ? so can it help, sir? – Ruby Man Feb 28 '14 at 08:09
  • ap? didnt you say the startup letter (one letter)? – Henrik Feb 28 '14 at 08:12
  • not only one, the search is like the search word in Dictionary. one letter , the one more letter, ... – Ruby Man Feb 28 '14 at 08:14
  • So you will be able to search for i.e.: a, ap, app, appl, apple to in this case get index 0 and if you only type the a letter you will get index 0 and 1 ? – Henrik Feb 28 '14 at 08:15
0

You can run some initialization code (before the user starts to type letters in).

// initialize an array that has a cell for each letter with value -1
int[] firstIndexes = new int[26];
for(int i=0;i<firstIndexes.length;i++) {
    firstIndexes[i] = -1;
}

// loop over original array and look for each letter's first occurence
for(int i=0;i<wordsArray.length;i++) {
    char c=wordsArray[i][0];
    if(firstIndexes[c-'a'] < 0) {
        firstIndexes[c-'a'] = i;
    }
}

Then when the user types a letter you just need to find its index in the 'firstIndexes' array.

meir shapiro
  • 647
  • 7
  • 16