簡體   English   中英

不使用 Array.sort 對多維字符串數組進行排序

[英]Sort Multidimensional String Array Without Using Array.sort

我是 Java 的新手,但為了擴展我的知識。 下面是我很難完成的課堂作業。 我需要創建一個方法,該方法傳入一個二維字符串數組,然后按第二個元素對數組進行排序。

方法 sortContacts()

  • 聲明為公共靜態方法,應以二維String數組為參數,數組中聯系人個數為整數值
  • 不返回任何內容 o 使用 lastName 作為排序字段對作為參數給出的聯系人列表的內容進行排序
  • 您可以使用文本中描述的任何排序機制(氣泡、插入或選擇)
  • 關鍵概念:在實現排序時,訣竅是確定要比較的值的維度以及它們與循環中的值的關系。
  • 提示:
  • 不要依賴數組的循環長度,而是使用聯系人數量中的值
  • 您的臨時變量將是一個大小為 3 的數組, String[] temp = new String[3];
  • 您將需要使用string1.compareTo(string2)方法來比較兩個字符串。

示例數據:(名字、姓氏、電話號碼)

String [][] contactsArray = { 

        {"Emily","Watson","913-555-0001"},
        {"Madison","Jacobs","913-555-0002"},
        {"Joshua","Cooper","913-555-0003"},
        {"Brandon","Alexander","913-555-0004"},
        {"Emma","Miller","913-555-0005"},
        {"Daniel","Ward","913-555-0006"},
        {"Olivia","Davis","913-555-0007"},
        {"Isaac","Torres","913-555-0008"},
        {"Austin","Morris","913-555-0009"}



public static void sortContact(String[][] contactsArray, int numContacts) {

    String[] temp = new String[3];
    String [] words = contactsArray[3];

    for(int i = 0; i < numContacts-1; i++)
    {
        int smallest = i;
        for(int j = i + 1; j < numContacts-1; j++) 
        {

            //Prints loop variables so I can see them before any action
            System.out.println("First: "+words[j]+" " +"Second "+words[i]);
            if(words[j].compareTo(words[i]) < 0)
                smallest = j;
        }

       //put the new minimum in the i-th position.

        //String temp = words[i];
        words[i] = words[smallest];
        words[smallest] = temp[i];
    }   
}

整數數組的例子有很多,但字符串數組的例子並不多,

任何建議表示贊賞。

我建議您閱讀 OOP 概念以及如何在 Java 中實現它們。 有數以百計的書籍,文章和教程在線一樣,像https://www.journaldev.com/12496/oops-concepts-java-examplehttps://beginnersbook.com/2013/04/oops-concepts /

至於答案,您應該創建一個擴展Comparable接口的類來表示二維數組中的每一行。 例如,創建一個名為Contact的類,它實現了Comparable接口。 從 Comparable 接口實現compareTo方法。 然后創建一個創建人員列表的驅動程序類並調用 Collections.sort(list)。

我有意將實現留給你,因為這是你的任務,這樣你就可以邊做邊學,而不是別人為你做。

有關 Comparable 接口,請參閱以下鏈接。 https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/

你可以這樣做:

 for(int i=0;i<numContacts;i++) {
        for(int j=i+1;j<numContacts;j++) {
            if(contactsArray [i][1].compareTo(contactsArray [j][1])>0) {
                String[] temp = contactsArray [i];
                contactsArray [i] = contactsArray [j];
                contactsArray [j] = temp;
            }
        }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM