Search an integer value in a json array of integers

I have a json array of integers which I have already sorted. So now I want to search an integer element inside the json array.(The size of the json array varies depending upon the situation, but it only contains integers and nothing else). What is the best way to make an efficient search?

Answers


You can do binary search of the array like:

1- Set min/max integer indexes to cover your whole float array

2- test the value in the middle of the range at index mid=(min+max/2) against the search value x

3- if x is lower than this value, set max to mid, else set min to mid

4- repeat (2-4) until you have found the correct value


As suggested by @Friar Bob, I used binary search to make the search. I first converted the json array into a List variable named selectedCatIds and used the below method to return true if the element is found else false. Thanks all for the help. Binary search indeed does the work efficiently.

 private boolean searchInSelectedIdsList(int storeCatId){
    int notFound = -1;
    int low=0,high=selectedCatIds.size()-1,mid =(low+high)/2;
    while(low<=high &&  selectedCatIds.get(mid)!=storeCatId){
        if(selectedCatIds.get(mid)<storeCatId)
            low = mid+1;
        else
            high = mid-1;
        mid = (low+high)/2;
    }
    if(low>high)
        mid=notFound;
    return (mid>=0);
}

var obj = "{\"array\":[\"key1\":\"value1\",\"key2\":\"value2\"]}";

var searchInt= int value;


for (var i = 0; i < obj.length; i++){

  if (obj[i].code == searchInt){

    // obj[i].name is the matched result
  }
}

Need Your Help

What is the proper way to point my module to a config directory using config.js?

node.js

I built a node module for others to import into their node projects. I use config.js. I'm having issues telling their scripts where to look for my config directory is.

Disable TSQL script check?

sql-server tsql

lets say I have a script like that: