Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually sorting an ArrayList of strings alphabetically in Java

I am trying to reorder an ArrayList alphabetically for an assignment. I am not allowed to use any methods for automatically sorting, it has to be done manually. This is the code I tried, but it does not even run. I appreciate any input on this.

import java.util.ArrayList;

public class SortArrayList {
    public static void main(String[] args) {
        ArrayList<String> values = new ArrayList<String>();
        public static void main(String[] args) {
        ArrayList<String> values = new ArrayList<String>();
        values.add("car");
        values.add("bear");
        values.add("apple");
        values.add("xray");
        sort(values);
        for (int i = 0; i < values.size(); i++)
            System.out.println(values.get(i));
    }

    public static void sort(ArrayList<String> x) {
        String temp;
        for (int i = 0; i < x.size() - 1; i++) {
            for (int j = i + 1; j < x.size(); j++) {
                if (x.get(i).compareToIgnoreCase(x.get(j)) > 0) {
                    temp = x.get(i);
                    x.add(i,x.get(j));
                    x.add(j,temp); 

                }
            }
        }
    }
}
like image 229
user5511508 Avatar asked Oct 19 '22 23:10

user5511508


1 Answers

The lines

x.add(i,x.get(j));
x.add(j,temp);

are adding more elements to the ArrayList. You should change them to

x.set(i, x.get(j));
x.set(j, temp);

so that it replaces the elements at those positions.

like image 89
badjr Avatar answered Oct 27 '22 17:10

badjr