Tuesday, August 13, 2013

Java Linear and Binary Searching - For my reference


public class Searching {

/**
* @param args
*/
public static void main(String[] args) {

int arrayNumbers[] = new int[] {55, 65, 76, 89, 123, 43, 56, 23, 11, 107, 98 };
int searchNumber = 89;
int pos = 0;
int posB = 0;
int unsortedArray[] = new int[arrayNumbers.length];
System.arraycopy( arrayNumbers, 0, unsortedArray, 0, arrayNumbers.length);
arrayNumbers = sort(arrayNumbers);

for (int i = 0; i < unsortedArray.length;i++){


pos = linearSearch(arrayNumbers, unsortedArray[i]);
posB = binarysearch(arrayNumbers, unsortedArray[i]);
System.out.println(unsortedArray[i] + "\t" + pos + "\t" + posB + "\t" + arrayNumbers[i]);
}
}

private static int binarysearch(int[] arrayNumbers, int i) {

int lower = 0;
int upper = arrayNumbers.length - 1;
int cur = 0;

while (true){

cur = (lower + upper) / 2;

if(i == arrayNumbers[cur])

return cur;
else if (lower > upper) 

return arrayNumbers.length;

else {

if(i > arrayNumbers[cur])

lower = cur + 1;

else 

upper = cur - 1;
}
}


}

private static int linearSearch(int[] arrayNumbers, int searchNumber) {

for(int i = 0; i < arrayNumbers.length; i++){

if(searchNumber == arrayNumbers[i]){

return i;
}

}
return 0;
}

public static int[] sort (int[] arrayNumbers){

int temp = 0;
for (int i = 0; i < arrayNumbers.length ; i ++ ){

for (int j = 0; j < arrayNumbers.length; j++) {

if(arrayNumbers[i] < arrayNumbers[j]){

temp = arrayNumbers[i];
arrayNumbers[i] = arrayNumbers[j];
arrayNumbers[j] = temp;
}
}
}
return arrayNumbers;
}
}


No comments: