Java - 仅排序数组的子部分

Sol*_*gon 8 java sorting

我有一个字符数组

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

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

// '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 
Run Code Online (Sandbox Code Playgroud)

emi*_*min 16

我认为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);
Run Code Online (Sandbox Code Playgroud)


Era*_*ran 5

使用公共静态无效的排序(的char []一,INT的fromIndex,INT toIndex)Arrays类.

在你的例子中:

Arrays.sort(chArr,2,6); // note that fromIndex is inclusive
                        // but toIndex is exclusive
Run Code Online (Sandbox Code Playgroud)