50% OFF!!!

Thursday, September 3, 2009

J2ME | Binary search algorithem


Binary search algorithem method/function for j2me platform.
Use is with sorted String array!!!
Enjoy... this works great with my example on J2ME | String array sort. link here.



public static int binarySearch(String[] p_arraySorted, String p_key)
{
return binarySearch(p_arraySorted, 0, p_arraySorted.length, p_key);
}



public static int binarySearch(String[] p_arraySorted, int p_first, int p_upto, String p_key)
{
int compare, mid;
while (p_first < p_upto)
{
// Compute mid point.
mid = (p_first + p_upto) / 2;

compare = p_key.compareTo(p_arraySorted[mid]);
if (compare < 0) // p_key < p_arraySorted[mid]
{
// repeat search in bottom half
p_upto = mid;
}
else if (compare > 0) // p_key > p_arraySorted[mid]
{
// Repeat search in top half
p_first = mid + 1;
}
else
{
// Found it. return position
return mid;
}
}

// Failed to find key
return -1;
}


Sort it and search it wisely...

J2ME | String array sort

Here is a good function for sorting string arrays.
The algorithem is BUBBLE-SORT algorithm.
The algorithem sorts the string array (dictionary comparison)


static void bubbleSort(String[] p_array) throws Exception
{
boolean anyCellSorted;
int length = p_array.length;
String tmp;
for (int i = length; --i >= 0;)
{
anyCellSorted = false;
for (int j = 0; j < i; j++)
{
if (p_array[j].compareTo(p_array[j + 1]) > 0)
{
tmp = p_array[j];
p_array[j] = p_array[j + 1];
p_array[j + 1] = tmp;
anyCellSorted = true;
}

}
if (anyCellSorted == false)
{
return;
}
}
}



if you want i will upload more SORT algorithems...