Java - 只对数组的子部分进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28386402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:30:58  来源:igfitidea点击:

Java - sort only subsection of array

javasorting

提问by SoluableNonagon

I have an array of characters

我有一个字符数组

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

What's the easiest way to sort only a section of the array, given a start and end index?

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

// '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 

回答by emin

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

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

回答by Eran

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

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

In your example:

在你的例子中:

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

回答by hoat4

Use Arrays.sort([], int startIndex, int endIndex).

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

回答by PaulBGD

Check out Arrays.sort().

查看Arrays.sort()

Example usage:

用法示例:

Arrays.sort(chhArr, 2, 5);