Sorting an ArrayList array of String arrays using the compareTo () method

I am new to java.

I am trying to sort an ArrayList array from String using String.compareTo() .

I compiled the code so that the output is:

Causality, is, relationship

This is also called causal.

This, is, oh, and, the reason, and her, affect

Now I want to sort this code (lexicographically) so that the output is:

Causality, and, this, relationship

This, also called a causal relationship, is

This, oh, oh, affect, and the reason, this, it

However, I am generating some crazy output.

My code is below.

Any help would be appreciated.

I worked on this, probably a very simple problem for several hours, and I am ready to destroy my computer. Thanks

 public class Wk5Q5 { void process1 () { String s1 = "Causality is a relationship"; String s2 = "It is also called causation"; String s3 = "It is about a cause and its affect"; ArrayList<String[]> list = new ArrayList<String[]>(); String[] arr1 = s1.split(" "); list.add(arr1); String[] arr2 = s2.split(" "); list.add(arr2); String[] arr3 = s3.split(" "); list.add(arr3); /** * previously sorted the arraylist of string arrays so that * each word is separated by commas */ for(int i = 0; i < list.size(); i++){ for (int j = 0; j < list.get(i).length; j++){ String t = list.get(i)[j]; if (j > 0){ t = ", " + t; } System.out.print(t); //System.out.println(list.get(i)[j]); } System.out.println(); } /** * my attempt at sorting each string in each list */ for(int z = 0; z < list.size(); z++){ for(int i = 0; i < list.get(z).length; i++){ String x = list.get(z)[i]; for (int j = i+1; j < list.get(z).length; j++){ String y = list.get(z)[j]; if(y.compareTo(x) < 0) { String temp = list.get(z)[i]; x = list.get(z)[j]; y = temp; } System.out.print(x); } } } } 
+4
source share
2 answers

The problem with implementing a sorting selection algorithm is that you are not modifying the sorted list. When you change x and y , the elements in the corresponding positions in the list remain in the same places.

If you stop using x and y and replace their use with list.get(z)[i] and list.get(z)[j] , your sorting algorithm will give different results. Even better, if homework allows you to use the standard library, check out the built-in way to sort arrays in Java .

+4
source

You can use Collections.sort as everyone else offers or does it manually. To do this manually, there are many different methods. You will want to use the quicksort or mergesort algorithm. If you do not know what it is, I can explain further; however, if it’s HW, you are likely to have bypassed them already

0
source

All Articles