/**
* @author Ilham Yuliantoro 105090600111028
*/
import java.util.Random;
import java.util.Scanner;
class laporan2 {
public int [] SelectionSort (int arr[]){
int minx;
for (int i=0;i
minx=i+1;
for (int j=minx+1;j
if(arr[j]
minx=j;
if(arr[minx]
int Temp=arr[i];
arr[i]=arr[minx];
arr[minx]=Temp;
}
}
return arr;
}
public int [] InsertionSort (int arr[]){
for (int i=0;i
int j=i;
int B=arr[i];
while ((j>0)&&(arr[j-1]>B)){
arr[j]=arr[j-1];
j--;
}
arr[j]=B;
}
return arr;
}
public int SequentialSearch (int arr[], int cari){
for (int i=0;i
if (arr[i]==cari)
return i;
return -1;
}
public int BinarySearch (int arr[], int cari){
boolean ketemu=false;
int indxkiri=0;
int indxkanan=arr.length-1;
int indxTengah=1;
while (!ketemu&&indxkiri<=indxkanan){
indxTengah=(indxkiri+indxkanan)/2;
if (arr[indxTengah]==cari)
return indxTengah;
else if (cari
indxkanan=indxTengah-1;
else
indxkiri=indxTengah+1;
}
return -1;
}
public void display(int arr[]){
for (int k=0;k
System.out.print(arr[k]+" ");
System.out.println();
}
public void acak(int arr[]){
Random acak = new Random();
for(int i=0;i
arr[i]=acak.nextInt(25);
}
}
public class Sorting_Searching{
public static void main(String[]args){
Scanner input = new Scanner (System.in);
laporan2 hasil=new laporan2();
int arr[]=new int[20];
int pil, bil;
long awal,akhir;
do{
System.out.println ("");
System.out.println ("Menu :");
System.out.println ("1. Selection Sort");
System.out.println ("2. Insertion Sort");
System.out.println ("3. Sequential Search");
System.out.println ("4. Binary Search");
System.out.println ("0. Keluar");
System.out.println ("");
System.out.print ("Masukkan Pilihan Anda :");
pil=input.nextInt();
switch (pil){
case 1 :
System.out.println ("");
hasil.acak(arr);
hasil.display(arr);
awal=System.nanoTime();
hasil.SelectionSort(arr);
akhir=System.nanoTime();
hasil.display(arr);
System.out.println ("Waktu proses :"+(akhir-awal));
break;
case 2 :
System.out.println ("");
hasil.acak(arr);
hasil.display(arr);
awal=System.nanoTime();
hasil.InsertionSort(arr);
akhir=System.nanoTime();
hasil.display(arr);
System.out.println ("Waktu proses :"+(akhir-awal));
break;
case 3 :
System.out.println ("");
hasil.acak(arr);
hasil.SelectionSort(arr);
hasil.display(arr);
System.out.println ("Masukkan bil yang ingin dicari :");
bil=input.nextInt();
awal=System.nanoTime();
System.out.println ("Bilangan tersebut terdapat pada index :"+hasil.SequentialSearch(arr,bil));
akhir=System.nanoTime();
System.out.println ("Waktu proses :"+(akhir-awal));
break;
case 4 :
System.out.println ("");
hasil.acak(arr);
hasil.SelectionSort(arr);
hasil.display(arr);
System.out.println ("Masukkan bil yang ingin dicari :");
bil=input.nextInt();
awal=System.nanoTime();
System.out.println ("Bilangan tersebut terdapat pada index :"+hasil.BinarySearch(arr,bil));
akhir=System.nanoTime();
System.out.println ("Waktu proses :"+(akhir-awal));
break;
}
}while (pil!=0);
}
}
0 komentar:
Posting Komentar