簡體   English   中英

如何在不使用Array.sort:Java的情況下按字母順序對數組進行排序

[英]How to sort array in alphabetical order without using Array.sort:Java

我想在Java中按字母順序對數組的值進行排序。我再次查看數組並獲得輸出。 我的目的是:遍歷單詞數組,找到最大的字符串(按字典順序排列),找到它后,在sortedWords數組的末尾插入單詞,將sortedArray的索引向左移動一個位置,減少原始數組刪除已經找到的單詞,再次循環找到下一個單詞....

謝謝你的幫助。

以下是我到目前為止所做的工作。

公共類Main {

public static void main(String[] args) {
    String[] words = {"bob","alice","keith","zoe","sarah","gary"};
    String[] sortedWords = new String[words.length];

    // Copy of the original array
    for(int i = 0; i < sortedWords.length;i++){
        sortedWords[i]= words[i];
    }


    for (int i = 0; i < words.length - 1; i++) {
    int currentSize = words.length;
    int position = 0;
    boolean found = false;
    while (position < currentSize && !found) {
        if (words[i].equals(largestAlphabetically(words))) {
            found = true;

        } else {
            position++;
        }
    }

        if(found){
            insertAtEnd(words,largestAlphabetically(words));
            shiftLeft(sortedWords,i);
            shorterArray(words);

        }

    }
    for(int i = 0;i < sortedWords.length;i++){
        System.out.println(sortedWords[i]);
    }

}


/**
 * This method inserts the largest string lexicographically at the end of the array
 * @param words
 * @param wordToInsert
 * @return an array with string at the end
 */

public static String [] insertAtEnd(String[] words, String wordToInsert) {

    for (int i = 0; i < words.length; i++) {
        int currentSize = words.length - 1;
        wordToInsert = largestAlphabetically(words);
        if (currentSize < words.length) {
            currentSize++;
            words[currentSize - 1] = wordToInsert;
        }
    }
    return words;
}

/**
 * This method determines the largest string in an array
 * @param words
 * @return largest string lexicographically
 */
public static String largestAlphabetically(String[] words) {
    String searchedValue = words[0];
    for (int i = 0; i < words.length; i++) {

        for (int j = 0; j < words.length; j++) {
            if (words[i].compareToIgnoreCase(words[j]) < 0) {
                searchedValue = words[j];
            }
        }
    }
    return searchedValue;
}

/**
 * To shift the array index to the left
 * @param dest
 * @param from
 */

public static void shiftLeft(String[] dest, int from) {
    for (int i = from + 1; i < dest.length; i++) {
        dest[i - 1] = dest[i];
    }
    dest[dest.length - 1] = dest[0];
}

/**
 * Remove the largest word from a string while maintaining the order of the array
 * @param words
 * @return return a shorter array
 */
public static String [] shorterArray(String[] words) {
    String [] shorterArray = new String[words.length];
    int currentSize = words.length;
    String searchedValue = largestAlphabetically(words);
    int position = 0;
    boolean found = false;
    while (position < currentSize && !found) {
        if (words[position] == searchedValue) {
            found = true;

        } else {
            position++;
        }
    }
    if (found) {
        for (int i = position + 1; i < currentSize; i++) {
            words[i - 1] = words[i];

        }
        currentSize--;
        shorterArray = words;
    }

    return shorterArray;

}

}

簡單的實現可以是這樣的:

String[] words = {"bob","alice","keith","zoe","sarah","gary"};

boolean isSwapped = false;
do {
    isSwapped = false;
    for(int i=0;i<words.length-1;i++){
        if(words[i].compareTo(words[i+1])>0){
            String temp = words[i+1];
            words[i+1] = words[i];
            words[i] = temp;
            isSwapped = true;
        }
    }
}while((isSwapped));

我不知道為什么你不想使用Arrays.sort()或Collections.sort(),無論如何,如果你真的想要實現一個簡單的排序算法,你可以從插入排序開始,如一些評論中所建議的那樣。 這是一個簡單的實現:

String[] words = {"bob","alice","keith","zoe","sarah","gary"};
for(int i = 0; i < words.length; i++)
{
    int smallest = i;
    for(int j = i + 1; j < words.length; j++) // here you find the index of the minimum String between the strings in the unsorted side of the array
    {
        if(words[j].compareTo(words[i]) < 0)
            smallest = j;
    }
    //put the new minimum in the i-th position.
    String aux = words[i];
    words[i] = words[smallest];
    words[smallest] = aux;
}
for(int i = 0; i < words.length; i++)
{
    System.out.println(words[i]);
}

請注意,這是就地排序,因此您不需要輔助數組。 希望很清楚

你可以像這樣比較兩個字符串:

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1

所以你可以寫一個小Blubblesort。 鏈接: https//en.wikipedia.org/wiki/Bubble_sort

堆排序似乎是按字典順序對數組字符串進行排序的最佳方法。 二進制最大堆將是要走的路。 在Java中,它可以使用PriorityQueue實現。

我使用PriorityQueue的自編程接口編寫了BinaryMinHeap 你會在這里找到這個項目。 [請注意不要在沒有引用的情況下復制任何代碼。]

這是否回答你的問題?

//使用可以對任何類型的數據進行排序的通用算法。 //選擇排序

public class Selection {
static public void sort(Comparable...a){
    int N = a.length;
    for(int i=0;i<N;i++){
        int min = i;
        for(int j=i+1;j<N;j++){
            if(less(a[j],a[min]))
                min = j;
            swap(a,i,min);
        }
    }
}

static private boolean less(Comparable a,Comparable b){
    return a.compareTo(b)<0;//return true if a is a-b<0;meaning a is less than b
}

static private void swap(Comparable[] a,int i,int j){
    Comparable temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

static public boolean isSorted(Comparable...a){
    int N = a.length;
    for(int i=1;i<N;i++){
        if(less(a[i],a[i-1]))//if a[i]<a[i-1] then the array is not in order. Eg. a[1]=5,a[(1-1=0)]=6 then the isNotSorted
            return false;
    }
    return true;
}

}

現在使用測試客戶端

public class MainClass{
    String[] words = {"bob","alice","keith","zoe","sarah","gary"};
    for(String word:words){System.out.println(e+" ");}//print the words before sorting
    words.sort(words);
    for(String word:words){System.out.println(e+" ");}//print the words after sorting
}

該算法可以對您想要的任何類型的數據進行排序。 例如。 String,Integer和實現Comparable的任何數據類型

 public boolean isSorted(String[] a) {
        for (int i = 0; i < a.length; i++) {
            if (a[i - 1].compareTo(a[i]) > 0) {
                return false;
            }
        }
        return true;
    }

暫無
暫無

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

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