Java – 仅排序数组的子部分

我有一个字符数组

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 

我认为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); 

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 

查看Arrays.sort() 。

用法示例:

 Arrays.sort(chhArr, 2, 5); 

使用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