SearchingApp.java
public class SearchingApp {
public static void main(String[] args){
int jml = Integer.parseInt(JOptionPane.showInputDialog("Masukkan Jumlah Data!"));
Searching data = new Searching(jml);
for(int i=0;i<jml;i++){
int isi = Integer.parseInt(JOptionPane.showInputDialog("Masukkan angka ke-"+(i+1)));
data.isi(isi);
}
System.out.println("Program Searching (sequential & binary)");
data.tampil();
int menu = Integer.parseInt(JOptionPane.showInputDialog("Searching\n1. sequential\n2. binary"));
switch(menu){
case 1:{
System.out.println("sequential search");
int cari = Integer.parseInt(JOptionPane.showInputDialog("Masukkan angka yang dicari!"));
int find = data.SeqSearch(cari);
if(find<0){
JOptionPane.showMessageDialog(null,"Maaf, Data tidak ditemukan");
System.out.println("Maaf, Data tidak ditemukan");
}else{
JOptionPane.showMessageDialog(null,"Data ditemukan pada array ke-"+find);
System.out.println("Data ditemukan pada array ke-"+find);
}
break;
}
case 2: {
System.out.println("binary search");
int cari = Integer.parseInt(JOptionPane.showInputDialog("Masukkan angka yang dicari!"));
data.insertionSort();
System.out.println("Sudah disorting");
data.tampil();
int find = data.binarySearch(cari);
if(find<0){
JOptionPane.showMessageDialog(null,"Maaf, Data tidak ditemukan");
System.out.println("Maaf, Data tidak ditemukan");
}else{
JOptionPane.showMessageDialog(null,"Data ditemukan pada array ke-"+find);
System.out.println("Data ditemukan pada array ke-"+find);
}
break;
}
default:{
JOptionPane.showMessageDialog(null,"Maaf, inputan anda salah");
break;
}
}
}
}
Searching.java
public class Searching {
private int[] a;
private int nElems;
public Searching(int max)
{
a = new int[max];
nElems = 0;
}
public void isi(int value)
{
a[nElems] = value;
nElems++;
}
public void tampil()
{
for(int j=0; j<nElems; j++){
System.out.print(a[j]+" ");
}
System.out.println("\n");
}
public void insertionSort()
{
int in, out;
for(out=1; out<nElems; out++)
{
int temp = a[out];
in = out;
while(in>0 && a[in-1] >= temp)
{
a[in] = a[in-1];
--in;
}
a[in] = temp;
}
}
public int SeqSearch(int key){
for (int i=0; i<a.length-1; i++)
if (a[i]==key)
return i;
return -1;
}
public int binarySearch(int key) {
int low = 0;
int high = a.length;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key)
return mid;
else if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}
Tidak ada komentar:
Posting Komentar