sequensial search & binary search dalam array

hari ini tugas java dikampus bener2 bikin pusing kepala. dosen nya killer baget,, neh dikase tugas buat program sequensial search and binary search. mumpung ada waktu cuman pengen sharing siapa tau bermanfaat untuk anda, nih source code nya :

import java.io.*;
class elemen
{
elemen(){}//konstuktor
boolean flag = false;
int counter = 0;
int idx = -1;
int idxAkhir;
int idxAwal = -1;
int k = -1;

private int [] array= new int [5];

elemen(int[]arr)
{
this.array = arr;
}
public void setarray(int[] arr)
{
this.array = arr;
}

public int []getarray()
{
return (this.array);
}

public void setidxAkhir(int idxa)
{
idxAkhir = idxa;
}
public int getidxAkhir()
{
return idxAkhir;
}

void print()
{
System.out.println(“data array :”);
for (int i = 0; i < 5 ; i++ )
{
System.out.println(“nilai ke [“+i+”] : “+array[i]);
}
}
void seqSearch(int cari)
{
for ( int i = 0; i < 5 ; i++ )
{
counter ++;
if (array [i] == cari)
{
idx = i;
flag = true;
break;
}
}
if ( flag == true)
{
System.out.println(“data ada di index ke : “+idx);
}
else
{
System.out.println(“data tak ada di index “);
}
}

void binSearch(int cari)
{
while ((flag == false) && (idxAwal <= idxAkhir))
{
counter ++;
k = (idxAwal + idxAkhir)/2;
if (array [k] == cari)
{
flag = true;
}
else
{
if (array [k] < cari)
{
idxAwal = k+1;
}
else
{
idxAkhir = k-1;
}
}

}

if ( flag == true)
{
System.out.println(“data ada di index ke : “+idx);
}
else
{
System.out.println(“data tak ada di index “);
}
}
}

class array
{
public static void main(String[] args)throws IOException
{

elemen nilArray = new elemen();
DataInputStream ta = new DataInputStream (System.in);
int [] array= new int [5];
//—————————————————————————–
for (int i = 0; i < 5 ; i++ )
{
System.out.print(“inputkan nilai ke [“+i+”] : “);
array[i] = Integer.parseInt(ta.readLine());
nilArray.setarray(array);
}

//—————————————————————————–
nilArray.print();

//—————————————————————————–
System.out.print(“inputkan nilai yg dicari : “);
int cari = Integer.parseInt(ta.readLine());
nilArray.seqSearch(cari);
nilArray.binSearch(cari);
nilArray.setidxAkhir(array.length);

}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s