Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - sort only subsection of array

Tags:

java

sorting

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 
like image 367
SoluableNonagon Avatar asked Feb 07 '15 19:02

SoluableNonagon


People also ask

How do you sort a range in Java?

sort(byte[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of bytes into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

How do I print part of an array?

You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.


1 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);
like image 88
emin Avatar answered Sep 21 '22 21:09

emin