Skip to content

Instantly share code, notes, and snippets.

@agungsijawir
Created May 13, 2013 18:45
Show Gist options
  • Save agungsijawir/5570450 to your computer and use it in GitHub Desktop.
Save agungsijawir/5570450 to your computer and use it in GitHub Desktop.
Sample code for Sequence and Binary Tree Search Algorithm Algorithm and Data Structure Class
/**
* Author: Agung Andika
*/
import java.util.ArrayList;
import java.util.Scanner;
public class Searching {
public static void main(String[] args) {
// dataList = ArrayList data type
// askData = how much array / data will be stored
// findWhat = ask users which data will be find (int data type)
// foundIndex = tell user if data found, where is location of its
// boolean found = false; send signal if data found
ArrayList<Integer> dataList = new ArrayList<Integer>(); // should be String for variant
int askData = 0, findWhat = 0, foundIndex = 0;
boolean found = false;
Scanner data = new Scanner(System.in);
System.out.print("How much data? "); askData = data.nextInt();
if (askData == 0) { System.out.println("0 data?"); System.exit(0); }
for( int i = 0 ; i < askData ; i++ ) {
System.out.print("#" + (i) + ": ");
dataList.add( data.nextInt() );
}
System.out.print("Find what? "); findWhat = data.nextInt();
// old style sequence directly
for (int i = 0; i < askData; i++) {
if (dataList.get(i) == findWhat) { found = true; foundIndex = i;}
else { found = false; }
}
System.out.println("Data '" + findWhat + "' found in index #" + foundIndex);
// parse by value from functions
if (SequenceSearchA(dataList, findWhat) == true) {
System.out.println("[Sequence] Data found!");
}
if (BinarySearchA(dataList, findWhat) == true) {
System.out.println("[Binary] Data found!");
}
}
static boolean SequenceSearchA(ArrayList<Integer> tmpData, int data) {
int dataSize = tmpData.size();
boolean resultsSearch = false;
for (int i = 0; i < dataSize; i++) {
if (tmpData.get(i) != data) resultsSearch = false;
else resultsSearch = true;
}
return resultsSearch;
}
static boolean BinarySearchA(ArrayList<Integer> tmpData, int dataBin) {
// we need to meassure array list size
int low = 0, high = tmpData.size() - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (dataBin > tmpData.get(middle) ) { low = middle + 1; }
else if (dataBin < tmpData.get(middle)) { high = middle - 1; }
else { // data found!
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment