Java - sort only a subsection of an array

I have an array of characters

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

What is the easiest way to sort only a section of an array, given the 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 
+4
source share
4 answers

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);
+11
source

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

In your example:

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

Arrays.sort().

:

Arrays.sort(chhArr, 2, 5);
+1

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
+1

All Articles