1

I have an array of strings that have 3 subsections that I am looking to sort. See the below example

String[] teams = new String[5];
teams[0] = "Header1";
teams[1] = "Candy";
teams[2] = "Apples";
teams[3] = "Fruit";
teams[4] = "Header2";
teams[5] = "Candy";
teams[6] = "ZZZ";
teams[7] = "Fruit"; 
teams[8] = "E";
teams[9] = "Header3";
teams[10] = "C";
teams[11] = "T";
teams[12] = "A";

I want to sort each of the subsections while leaving the Headers1-3 in place. Should I break up my array into 3 sub arrays based off of the known entries (Headers1-3) and just use array.sort or is there an easier way that I am unaware of? Note my string array is a fixed length of entries and each Header is in a known position (i.e Header 2 is always in position 4).

2
  • You should learn about objects and classes. Java is an OO language. You should have a List<Section>, containing 3 objects. Each object would have a title (String), and probably a List<String> elements. You could now easily sort each List<Element> inside each Section object. Don't mix unrelated things in the same array or collection. Don't use arrays in general, and prefer collections. Commented Aug 10, 2018 at 21:21
  • 1
    Also, you can't possbly store 13 elements in an array of length 5. Commented Aug 10, 2018 at 21:22

1 Answer 1

4

I think you are almost there. Using Arrays.sort and specifying the indices seems the easiest.

public static void sort(int[] arr, int from_Index, int to_Index)

The range is defined as follows

The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

In this example, using the following code:

Arrays.sort(teams,1,4);
Arrays.sort(teams,5,9);
Arrays.sort(teams,10,13);

for (String s : teams) {
    System.out.println(s);
}

produces the following output:

Header1
Apples
Candy
Fruit
Header2
Candy
E
Fruit
ZZZ
Header3
A
C
T

I would suggest not to keep your dataset that way because there are better ways to organize the data than to fit them into a single array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.