Java - sort only subsection of array

那年仲夏 提交于 2020-01-30 04:33:11

问题


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 

回答1:


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);



回答2:


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



回答3:


Check out Arrays.sort().

Example usage:

Arrays.sort(chhArr, 2, 5);



回答4:


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


来源:https://stackoverflow.com/questions/28386402/java-sort-only-subsection-of-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!