Java - sort only subsection of array

前端 未结 4 472
不思量自难忘°
不思量自难忘° 2021-01-17 14:56

I have an array of characters

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

相关标签:
4条回答
  • 2021-01-17 15:21

    Check out Arrays.sort().

    Example usage:

    Arrays.sort(chhArr, 2, 5);
    
    0 讨论(0)
  • 2021-01-17 15:36

    I think public static void sort(char[] a, int fromIndex, int toIndex) answers your question.

    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);
    
    0 讨论(0)
  • 2021-01-17 15:37

    Use public static void sort(char[] a, int fromIndex, int toIndex) in Arrays class.

    In your example:

    Arrays.sort(chArr,2,6); // note that fromIndex is inclusive
                            // but toIndex is exclusive
    
    0 讨论(0)
  • 2021-01-17 15:38

    Use 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
    
    0 讨论(0)
提交回复
热议问题