【问题标题】:Java - sort only subsection of arrayJava - 仅排序数组的子部分
【发布时间】:2015-02-07 19:30:10
【问题描述】:

我有一个字符数组

String a = "badabcde";
char[] chArr = a.toCharArray(); // 'b','a','d','a','b','c','d','e'

在给定开始和结束索引的情况下,仅对数组的一部分进行排序的最简单方法是什么?

// 'b','a','d','a','b','c','d','e'
subSort(array, startIndex, endIndex);

Ex: 
subSort(chArr, 2, 5);
// 'b','a','a','b','c','d','d','e' // sorts indices 2 to 5 

【问题讨论】:

    标签: java sorting


    【解决方案1】:

    我认为public static void sort(char[] a, int fromIndex, int toIndex) 回答了你的问题。

    String a = "badabcde";
    char[] chArr = a.toCharArray(); // 'b','a','d','a','b','c','d','e'
    
    // fromIndex - the index of the first element (inclusive) to be sorted
    // toIndex - the index of the last element (exclusive) to be sorted
    Arrays.sort(chArr,2,6);
    

    【讨论】:

      【解决方案2】:

      Arrays 类中使用public static void sort(char[] a, int fromIndex, int toIndex)

      在你的例子中:

      Arrays.sort(chArr,2,6); // note that fromIndex is inclusive
                              // but toIndex is exclusive
      

      【讨论】:

        【解决方案3】:

        使用Arrays.sort([], int startIndex, int endIndex)

         String a = "badabcde";
         char[] chArr = a.toCharArray(); // 'b','a','d','a','b','c','d','e'
         Arrays.sort(chArr, 2, 5);
         System.out.println(new String(chArr)); // this prints baabdcde
        

        【讨论】:

          【解决方案4】:

          查看Arrays.sort()

          示例用法:

          Arrays.sort(chhArr, 2, 5);
          

          【讨论】:

            猜你喜欢
            • 2020-04-08
            • 2020-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-28
            • 1970-01-01
            • 1970-01-01
            • 2012-09-14
            相关资源
            最近更新 更多