【问题标题】:How to sort array in alphabetical order without using Array.sort:Java如何在不使用 Array.sort:Java 的情况下按字母顺序对数组进行排序
【发布时间】:2016-04-28 17:47:40
【问题描述】:

我想在 Java 中按字母顺序对数组的值进行排序。我被困在再次遍历数组并获取输出。 我的意图是: 遍历单词数组, 找到最大的字符串(按字典顺序), 找到后,将单词插入 sortedWords 数组的末尾, 将 sortedArray 的索引向左移动一位, 通过删除已经找到的单词来减少原始数组, 再次循环查找下一个单词....

感谢您的帮助。

以下是我到目前为止所做的。

公共类主{

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;

}

}

【问题讨论】:

  • “我被困在再次遍历数组并获得输出。”你在底部的循环完美地做到了。
  • 我建议你看看某些排序算法,因为你的不是很有效。
  • 呃,这段代码让我头疼!此外,您还没有说您的问题在哪里或到底是什么。如果您想编写自己的排序算法,请以insertion sort 为基础。
  • 感谢您的建议。我真的很感激他们。

标签: java arrays string sorting insert


【解决方案1】:
 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;
    }

【讨论】:

    【解决方案2】:

    //使用可以对任何类型的数据进行排序的通用算法。 //选择排序

    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 的数据类型

    【讨论】:

      【解决方案3】:

      我不知道你为什么不想使用 Arrays.sort() 或 Collections.sort(),无论如何,如果你真的想实现一个简单的排序算法,你可以按照一些 cmets 中的建议从插入排序开始. 这是一个简单的实现:

      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]);
      }
      

      请注意,这是就地排序,因此您不需要辅助数组。 希望清楚

      【讨论】:

      • 谢谢。我的复杂程度超出了要求。
      • 没问题 :) 我能问一下您为什么将另一个答案标记为正确答案吗?
      【解决方案4】:

      简单的实现可以是这样的:

      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));
      

      【讨论】:

        【解决方案5】:

        堆排序似乎是按字典顺序对数组字符串进行排序的最佳方式。二元最大堆将是要走的路。在Java中,可以使用PriorityQueue来实现。

        我使用PriorityQueue 的自写界面编写了BinaryMinHeap。你会发现项目here。 [请注意不要在没有引用的情况下复制任何代码。]

        这能回答你的问题吗?

        【讨论】:

          【解决方案6】:

          你可以像这样比较两个字符串:

          "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

          【讨论】:

            猜你喜欢
            • 2021-09-25
            • 2019-12-01
            • 2014-11-13
            • 1970-01-01
            • 2015-05-17
            • 2020-02-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多