您如何在Java程序中实现对对象数组的跳转搜索?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了您如何在Java程序中实现对对象数组的跳转搜索?相关的知识,希望对你有一定的参考价值。

因此,我仍在学习Java,并且正在尝试实现跳转搜索以在对象数组中基于no_resi查找数据。

我了解它是如何处理int数组的,但是我仍然对如何使用对象数组感到困惑。我已经尝试过使用它来做一些事情,但仍然无法摆脱它,或者我只是愚蠢。

感谢您提供的任何帮助!

这是我的代码

JumpSearch.java

public class JumpSearch 

    public static int jumpsearch(Pengiriman[] arrayPengiriman, int no_resi) 

        int n = arrayPengiriman.length; 

        // Mencari ukuran blok untuk dilompati
        int step = (int)Math.floor(Math.sqrt(n)); 


        // Mencari blok tempat elemen berada
        // present (kalau elemet present) 
        int prev = 0; 
        while (arrayPengiriman[1-Math.min(step, n)] < no_resi)
         
            prev = step; 
            step += (int)Math.floor(Math.sqrt(n)); 
            if (prev >= n) 
                return -1; 
         

        // Melakukan linear search untuk x di dalam blok
        // dimulai dengan prev
        while (arrayPengiriman[1-Math.min(step, n)] < no_resi) 
         
            prev++; 

            // Jika mencapai blok berikutnya atau akhir
            // array, elemen tidak ada.
            if (prev == Math.min(step, n)) 
                return -1; 
         

        // Jika elemen ditemukan
        if (arrayPengiriman[prev] == no_resi) 
            return prev; 

        return -1; 
     


    // Program untuk menguji fungsi
    public static void main(String [ ] args) 
          
        Scanner scan = new Scanner(System.in);

        System.out.println("|==============================================================================|");
        System.out.println("|    PROGRAM PENCARIAN DATA PENGIRIMAN BARANG DENGAN ALGORITMA JUMP SEARCH     |");
        System.out.println("|==============================================================================|");
        System.out.println("|Kasus Mencari Data Pengiriman Dengan No.Resi Menggunakan Algoritma Jump Search|");   
        System.out.println("");

        // Array untuk menampung nilai tiap Data
        Pengiriman[] arrayPengiriman = new Pengiriman[16];                 

        Pengiriman kirim1 = new Pengiriman (101101,"Adam Kamil","Jl.Anggrek","Bogor","Gunungbatu","16118"); 
        Pengiriman kirim2 = new Pengiriman (101102,"Putra Mandala","Jl.Apel","Kerawang","Kerawang Barat","41311"); 
        Pengiriman kirim3 = new Pengiriman (101103,"Mamat Sanusi","Jl.Merpati","Jakarta Selatan","Lenteng Agung","12610"); 
        Pengiriman kirim4 = new Pengiriman (101104,"Kamila Akhwan","Jl.Kelapa","Bekasi","Bekasi Timur","17111"); 
        Pengiriman kirim5 = new Pengiriman (101105,"Putra Iskandar","Jl.Anggrek 2","Bogor","Menteng","16111"); 
        Pengiriman kirim6 = new Pengiriman (101106,"Nabila Putri","Jl.Merapi","Palu","Tatanga","94239");
        Pengiriman kirim7 = new Pengiriman (101107,"Imam Satya","Jl.Pulau Nias","Manado","Bunaken","95231"); 
        Pengiriman kirim8 = new Pengiriman (101108,"Robby Dermawan","Jl.Tajung Pura","Yogyakarta","Gondokusuman","55225"); 
        Pengiriman kirim9 = new Pengiriman (101109,"Adrian Suta","Jl.Dewi Sartika","Banggai","Luwuk","94712"); 
        Pengiriman kirim10= new Pengiriman (1011010,"Rizky Prima","Jl.Gunung Jati","Jayawijaya","Wamena","99511"); 
        Pengiriman kirim11 = new Pengiriman (1011011,"Margareth Warouw","Jl.Sawit","Jakarta Timur","Cibubur","13720"); 
        Pengiriman kirim12 = new Pengiriman (1011012,"Jeni Indira","Jl.Tuna","Bekasi","Bekasi Barat","17136"); 
        Pengiriman kirim13 = new Pengiriman (1011013,"Asep Suratman","Jl.Palapa","Bogor","Margajaya","16116"); 
        Pengiriman kirim14 = new Pengiriman (1011014,"Gigi Purnama","Jl.Keraton Atas","Bekasi","Setu","17320"); 
        Pengiriman kirim15 = new Pengiriman (1011015,"Kamila Dewi","Jl.Dago Timur","Bandung","Coblong","40135"); 
        Pengiriman kirim16 = new Pengiriman (1011016,"Desy Sambeta","Jl.Proklamasi","Surabaya","Wonocolo","60239"); 

        //memasukan data mahasiswa ke dalam array
        arrayPengiriman[0]=kirim1;
        arrayPengiriman[1]=kirim2;
        arrayPengiriman[2]=kirim3;
        arrayPengiriman[3]=kirim4;
        arrayPengiriman[4]=kirim5;
        arrayPengiriman[5]=kirim6;
        arrayPengiriman[6]=kirim7;
        arrayPengiriman[7]=kirim8;
        arrayPengiriman[8]=kirim9;
        arrayPengiriman[9]=kirim10;
        arrayPengiriman[10]=kirim11;
        arrayPengiriman[11]=kirim12;
        arrayPengiriman[12]=kirim13;
        arrayPengiriman[13]=kirim14;
        arrayPengiriman[14]=kirim15;
        arrayPengiriman[15]=kirim16;



        Pengiriman tampilPengiriman = new Pengiriman();

        System.out.println("|==============================================================================|");
        System.out.println("|                                DATA PENGIRIMAN                               |");
        System.out.println("|==============================================================================|");
        System.out.println("");

        for(int i = 0; i < 16; i++)
        //Menampilkan Array yang sudah disorting secara Ascending    
        tampilPengiriman = arrayPengiriman[i];

        System.out.print("  "+(i+1)+". ");
        System.out.print(tampilPengiriman.getNoResi()+" ");
        System.out.print(tampilPengiriman.getNamaPengirim()+" ");
        System.out.print(tampilPengiriman.getAlamatTujuan()+" ");
        System.out.print(tampilPengiriman.getKotaTujuan()+" ");
        System.out.print(tampilPengiriman.getKecamatanTujuan()+" ");
        System.out.println(tampilPengiriman.getKodePosTujuan()+" ");

        

        System.out.println("");
        System.out.println("--------------------------------------------------------------------------------");


        System.out.println("|==============================================================================|");
        System.out.println("|                               CARI DATA PENGIRIMAN                           |");
        System.out.println("|==============================================================================|");
        System.out.println("");

        //Memasukan 'noRes'
        System.out.print("\n    Masukkan No Resi yang ingin dicari datanya : ");
        int no_resi = scan.nextInt(); 

        // Mencari index dari 'x' dengan jump search
        int index = jumpsearch(arrayPengiriman, no_resi); 

        System.out.println("");
        System.out.println("--------------------------------------------------------------------------------");


        System.out.println("|==============================================================================|");
        System.out.println("|                       HASIL PENCARIAN DATA PENGIRIMAN                        |");
        System.out.println("|==============================================================================|");
        System.out.println("");

        // Menampilkan index dimana 'x' ditemukan
        if (no_resi != -1 && index != -1) 
          System.out.println("\n Data pengiriman barang dengan" + no_resi + 
                            " ditemukan di index ke " + index); 
         else 
          System.out.println("\n Data pengiriman dengan No Resi" + no_resi + 
                            " tidak ditemukan"); 
        
        System.out.println("|==============================================================================|");
    

Pengirman.java

public class Pengiriman

    private int no_resi;
    private String nama_pengirim;
    private String alamat_tujuan;
    private String kota_tujuan;
    private String kecamatan_tujuan;
    private String kode_pos_tujuan;

    public Pengiriman()
        this.no_resi = 0;
        this.nama_pengirim = "";
        this.alamat_tujuan = "";
        this.kota_tujuan = "";
        this.kecamatan_tujuan = "";
        this.kode_pos_tujuan = "";
    

    public Pengiriman(int no_resi,String nama_pengirim, String alamat_tujuan,
            String kota_tujuan, String kecamatan_tujuan, String kode_pos_tujuan)
        this.no_resi = no_resi;
        this.nama_pengirim = nama_pengirim;
        this.alamat_tujuan = alamat_tujuan;
        this.kota_tujuan = kota_tujuan;
        this.kecamatan_tujuan = kecamatan_tujuan;
        this.kode_pos_tujuan = kode_pos_tujuan;
    

    public int getNoResi() 
        return no_resi;
    
    public void setNoResi(int no_resi) 
        this.no_resi = no_resi;
    
    public String getNamaPengirim() 
        return nama_pengirim;
    
    public void setNamaPengirim (String nama_pengirim) 
        this.nama_pengirim = nama_pengirim;     
     
    public String getAlamatTujuan() 
        return alamat_tujuan;
    
    public void setAlamatTujuan (String alamat_tujuan) 
        this.alamat_tujuan = alamat_tujuan;     
     
    public String getKotaTujuan() 
        return kota_tujuan;
    
    public void setKotaTujuan (String kota_tujuan) 
        this.kota_tujuan = kota_tujuan;     
     
    public String getKecamatanTujuan() 
        return kecamatan_tujuan;
    
    public void setKecamatanTujuan (String kecamatan_tujuan) 
        this.kecamatan_tujuan = kecamatan_tujuan;     
         
    public String getKodePosTujuan()
        return kode_pos_tujuan;
    
    public void setKodePosTujuan (String kode_pos_tujuan) 
        this.kode_pos_tujuan = kode_pos_tujuan;     
        

答案

在大多数情况下,您的代码可以正常工作,但是这里需要注意一些小事情,还有其他需要考虑的事情。让我们从Pengiriman类开始。

Pengiriman类中,您有一个典型的构造函数,该构造函数不接受任何参数,并且在该构造函数中,您将所有类成员变量默认为0或Null String(“”)。如果仅在声明的位置初始化变量,则可以消除此附加代码。每当创建Pengiriman的新实例时,这将使这些值成为默认值,例如:

public class Pengiriman

    private int no_resi = 0;
    private String nama_pengirim = "";
    private String alamat_tujuan = "";
    private String kota_tujuan = "";
    private String kecamatan_tujuan = "";
    private String kode_pos_tujuan = "";

    public Pengiriman()  

    // ....     Overloaded Contructor(s)      ....

    // ....       Getters and Setters         ....  

    // ....  Nice to have a toString() method  ....

如果使用上面的构造方法,则需要使用Setter类方法来填充变量,而不使用它们初始化时使用的默认值:

Pengiriman p = new Pengiriman();
p.setNoResi(101109);

您在类中的其他(超载)构造函数接受所有类成员变量作为参数。这很好,并且在创建对象数组时使生活更轻松一些,因此,在创建数组时,您需要做的只是:

Pengiriman[] arrayPengiriman = new Pengiriman[16];

arrayPengiriman[0] = new Pengiriman(101101, "Adam Kamil", "Jl.Anggrek", "Bogor", "Gunungbatu", "16118");
arrayPengiriman[1] = new Pengiriman(101102, "Putra Mandala", "Jl.Apel", "Kerawang", "Kerawang Barat", "41311");
arrayPengiriman[2] = new Pengiriman(101103, "Mamat Sanusi", "Jl.Merpati", "Jakarta Selatan", "Lenteng Agung", "12610");
// .....  etc.  .....

不要也需要执行类似的操作(因此可以将其删除):

arrayPengiriman[0] = kirim1;
arrayPengiriman[1] = kirim2;
arrayPengiriman[2] = kirim3;
arrayPengiriman[3] = kirim4;
arrayPengiriman[4] = kirim5;
arrayPengiriman[5] = kirim6;
arrayPengiriman[6] = kirim7;
arrayPengiriman[7] = kirim8;
arrayPengiriman[8] = kirim9;
arrayPengiriman[9] = kirim10;
arrayPengiriman[10] = kirim11;
arrayPengiriman[11] = kirim12;
arrayPengiriman[12] = kirim13;
arrayPengiriman[13] = kirim14;
arrayPengiriman[14] = kirim15;
arrayPengiriman[15] = kirim16;

也无需创建额外的Array来保存用于排序的相同值。如果已经有数组,为什么要这样做?只需对原始数组进行排序。您正在使用的代码始终不会对数组进行排序。它仅显示元素。您应该在Pengiriman类中使用toString()方法来执行此操作:

要对对象数组进行排序,您需要确定要按升序对对象数据进行排序的对象。当然,逻辑选择是通过收据编号(no_resi)。要按对象的任何属性对对象进行排序,必须使该对象实现Comparable接口并重写compareTo()方法。

//Your class must start with:
public class Pengiriman implements Comparable<Pengiriman> 

然后在Pengiriman类的某个地方:

// Sort by Receipt Number in 'Ascending Order'.
@Override
public int compareTo(Pengiriman comparePengiriman) 
    int compareNoResi = comparePengiriman.getNoResi();

    //ascending order
    return this.no_resi - compareNoResi;

    // If you want Descending order then use this instead:
    // return compareNoResi - this.no_resi;

因为现在您在Pengiriman类中将有一个[[compareTo()方法,要对数组进行排序,您只需要使用以下代码行即可:

// Sort the Object Array Arrays.sort(arrayPengiriman);
您应该在

Pengiriman

类中使用的另一个方法是toString()方法,例如:// Somewhere in the Pengiriman class: @Override public String toString() return no_resi + ", " + nama_pengirim + ", " + alamat_tujuan + ", " + kota_tujuan + ", " + kecamatan_tujuan + ", " + kode_pos_tujuan;
此方法消除了通过单个方法调用从所有对象数据构建字符串的需要,例如:

System.out.println(arrayPengiriman[8].toString());

将在控制台窗口中显示:

101109, Adrian Suta, Jl.Dewi Sartika, Banggai, Luwuk, 94712

因此,以上所有实现都将显示为Array:

// Sort the Object Array Arrays.sort(arrayPengiriman); System.out.println("|==============================================================================|"); System.out.println("| DATA PENGIRIMAN |"); System.out.println("|==============================================================================|"); System.out.println(""); // Displays the Sorted Array for (int i = 0; i < 16; i++) System.out.print(" " + (i + 1) + ". " + arrayPengiriman[i].toString());

现在是

JumpSearch

类。我知道我们已经接触了该类的大部分内容,但是我想专注于jumpsearch()方法,因为在这种特定方法中,您遇到了很多主要问题。 现在,我们知道跳转搜索应该如何工作,并且它应该仅对

sorted

数组起作用。事情是有序的,这包括如何实现while循环的条件。以您使用的条件为例:while (arrayPengiriman[1 - Math.min(step, n)] < no_resi)
考虑用于获取

arrayPengiriman

数组元素的索引值的该方程式:1 - Math.min(step, n)。将Math.min(step, n) from的值减去1的值,换句话说就是1 - (calculated index value)。您认为最终会得到什么样的指数值?确实... ArrayIndexOutOfBoundsException!它应该是:从Math.min(step, n)减去1或换句话说(calculated index value) - 1while (arrayPengiriman[Math.min(step, n) - 1] < no_resi)
但是这只是此[[while
循环条件的一部分问题。我们要检查数组的哪一部分,以查看它是否小于(no_resi? arrayPengiriman [n]Pengiriman的对象实例,不能应用于该实例的所有属性。您将需要告诉它要比较该对象实例的哪个属性。在这种特殊情况下,它是no_resi(收据编号)属性,因此您需要通过以下方式进行操作:while (arrayPengiriman[Math.min(step, n) - 1].getNoResi() < no_resi) 是,您需要获取该特定对象实例的收据编号,以便对照用户提供的收据编号进行检查。再举一个例子,如果您碰巧想要该特定对象实例中的
发件人名称
,则可以执行以下操作:

String senderName = arrayPengiriman[12].getNamaPengirim(); 您在

jumpsearch()
方法中的第二个[[while

循环)完全包含错误的条件。应该是:

while (arrayPengiriman[prev].getNoResi() < no_resi) 我确定这是复制/粘贴问题,因为它与第一个while循环的条件相同。 :)但是请注意,如何应用Getter方法(

getNoResi()
)。您在

jumpsearch()方法中最后的IF语句条件也需要使用此Getter方法:

if (arrayPengiriman[prev].getNoResi() == no_resi) return prev; 我想你明白了。这应该可以解决您的问题。
The 

JumpSearch

类别:
public class JumpSearch public static int jumpsearch(Pengiriman[] arrayPengiriman, int no_resi) int n = arrayPengiriman.length; // Find the block size to skip int step = (int) Math.floor(Math.sqrt(n)); // Finds the block where the element is located // present (if element present) int prev = 0; while (arrayPengiriman[Math.min(step, n) - 1].getNoResi() < no_resi) prev = step; step += (int) Math.floor(Math.sqrt(n)); if (prev >= n) return -1; // Perform a linear search for x in blocks // starts with prev while (arrayPengiriman[prev].getNoResi() < no_resi) prev++; // If you reach the next or last block // array, missing element. if (prev == Math.min(step, n)) return -1; // If an element is found if (arrayPengiriman[prev].getNoResi() == no_resi) return prev; return -1; // Program for functional testing public static void main(String[] args) Scanner scan = new Scanner(System.in); System.out.println("|==============================================================================|"); System.out.println("| PROGRAM PENCARIAN DATA PENGIRIMAN BARANG DENGAN ALGORITMA JUMP SEARCH |"); System.out.println("|==============================================================================|"); System.out.println("| Case Finding Shipping Data With Recession Using Jump Search Algorithm |"); System.out.println(""); // Array untuk menampung nilai tiap Data Pengiriman[] arrayPengiriman = new Pengiriman[16]; arrayPengiriman[0] = new Pengiriman(101101, "Adam Kamil", "Jl.Anggrek", "Bogor", "Gunungbatu", "16118"); arrayPengiriman[1] = new Pengiriman(101102, "Putra Mandala", "Jl.Apel", "Kerawang", "Kerawang Barat", "41311");

以上是关于您如何在Java程序中实现对对象数组的跳转搜索?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Postgresql 中实现对复杂嵌套 JSONB 的全文搜索

C# Winform中如何实现窗体之间的跳转

如何在与MongoDB集成的Spring boot Elastic Search中实现对非结构化数据的搜索

Java中实现对集合中对象按中文首字母排序

如何在安卓开发中实现对listview的增删改查与刷新

如何在 RecyclerView 的 CardView 中实现对 Item Click 的操作以显示结果

(c)2006-2024 SYSTEM All Rights Reserved IT常识