Liniear Sort - Java Console

Berikut merupakan contoh sederhana script kode untuk pencarian data dalam array dengan metode liniear sort

import java.util.*;

public class LinearSearch {

        public int cari(String[] data, String key) {
                for (int i = 0; i < data.length; ++i) {
                        if (data[i].compareTo(key) > 0)
                                return -1;
                        else if (data[i].compareTo(key) == 0)
                                return i;
                }
                return -1;
        }

        public static void main(String[] args) {
                String nama[] = { "abud", "bambang", "cecep", "dedi", "eko", "feri",
                "gunawan", "hasan", "iwan", "jumeno", "karti", "lina", "murni" };
                String[] JK = {"L","L","L","L","L","L","L","L","L","L","P","p","P"};
                int[] umur = {23,21,35,28,20,17,18,20,34,26,17,22,21};

                {
                int indeksTerakhir = nama.length - 1;
                    for (int i = 0; i <= indeksTerakhir; i++)
                         System.out.println("" +i +"    Nama = "+nama[i]+
                         "   \tJenisKelamin = "+JK[i]+"  \tUmur = "+umur[i]);
                }
                LinearSearch search = new LinearSearch();
                String namaCari="";
                Scanner input = new Scanner(System.in);
                System.out.print("Masukkan nama yang dicari: ");
                namaCari = input.nextLine();
                int n = search.cari(nama, namaCari);

                if ((n >= 0) && (n < nama.length)) {
                        System.out.println("ketemu pada posisi ke: " + (n+1));
                } else {
                        System.out.println("Data yang dicari tidak ada");
                }
        }
}

Comments

Popular posts from this blog

Shenzhen Hi-tec network Technology co. Ltd

Network Technology course

Network Technology book Pdf