简体   繁体   中英

How to sort an ArrayList

All I need is the simplest method of sorting an ArrayList that does not use the in-built Java sorter. Currently I change my ArrayList to an Array and use a liner sorting code, but I later need to call on some elements and ArrayLists are easier to do that.

you can use anonymous sort.

Collections.sort(<ArrayList name>, Comparator<T>() {

    public int compare(T o1, T o2) {
    .....
    ....
    }      
});

where T is the type you want to sort (ie String, Objects) and simply implement the Comparator interface to your own needs

Assuming an ArrayList<String> a ...

Easiest (but I'm guessing this is what you're saying you can't use):

Collections.sort(a);

Next easiest (but a waste):

a = new ArrayList<String>(new TreeSet<String>(a));

Assuming "in-built sort" refers to Collections.sort() and you are fine with the sorting algorithm you have implemented, you can just convert your sorted array into an ArrayList

ArrayList list = new ArrayList(Arrays.asList(sortedArray));

Alternatively, you can rewrite your sorting algorithm to work with a List (such as an ArrayList) instead of an array by using the get(int index) and set(int index, E element) methods.

Sorting Arguments passed through Command prompt; without using Arrays.sort

public class Sort {

    public static void main(String args[]) 
    {
        for(int j = 0; j < args.length; j++) 
        {
            for(int i = j + 1; i < args.length; i++) 
            {
                if(args[i].compareTo(args[j]) < 0) 
                {
                    String t = args[j];
                    args[j] = args[i];
                    args[i] = t;
                }
            }
            System.out.println(args[j]);
        }
    }
}

By using Array.sort

import java.util.*;
public class IntegerArray {

    public static void main(String args[])
    {
        int[] num=new int[]{10, 15, 20, 25, 12, 14};
    Arrays.sort(num);
        System.out.println("Ascending order: ");
        for (int i=0; i<num.length; i++)
            System.out.print(num[i] + " ");
        }
}

Check for Comparator in java. You can implement your own sorting using this and use Collections.sort(..) to sort the arraylist using your own Comparator

If i remember correctly when you pull an element out of the middle of an arrayList it moves the rest of the elements down automaticly. If you do a loop that looks for the lowest value and pull it out then place it at the end of the arrayList. On each pass i-- for the index. That is use one less. So on a 10 element list you will look at all 10 elements take the lowest one and append it to the end. Then you will look at the first nine and take the lowest of it out and append it to the end. Then the first 8 and so on till the list is sorted.

If you are meant to sort the array yourself, then one of the simplest algorithms is bubble sort. This works by making multiple passes through the array, comparing adjacent pairs of elements, and swapping them if the left one is larger than the right one.

Since this is homework, I'll leave it to you to figure out the rest. Start by visualizing your algorithm, then think about how many passes your algorithm needs to make, and where it needs to start each pass. Then code it.

You also need to understand and solve the problem of how you compare a pair of array elements:

  • If the elements are instances of a primitive type, you just use a relational operator.
  • If the elements are instances of reference types, you'll need to use either the Comparable or Comparator interface. Look them up in the javadocs. (And looking them up is part of your homework ...)

Here is a "simple" quicksort implementation:

public Comparable<Object>[] quickSort(Comparable<Object>[] array) {
    if (array.length <= 1) {
        return array;
    }

    List<Comparable<Object>> less = new ArrayList<Comparable<Object>>();
    List<Comparable<Object>> greater = new ArrayList<Comparable<Object>>();
    Comparable<Object> pivot = array[array.length / 2];

    for (int i = 0;i < array.length;i++) {
        if (array[i].equals(pivot)) {
            continue;
        }
        if (array[i].compareTo(pivot) <= 0) {
            less.add(array[i]);
        } else {
            greater.add(array[i]);
        }
    }

    List<Comparable<Object>> result = new ArrayList<Comparable<Object>>(array.length);
    result.addAll(Arrays.asList(quickSort(less.toArray(new Comparable<Object>[less.size()]))));
    result.add(pivot);
    result.addAll(Arrays.asList(quickSort(greater.toArray(new Comparable<Object>[greater.size()]))));
    return result.toArray(new Comparable<Object>[result.size()]);
}

The last operations with arrays and list to build the result can be enhanced using System.arraycopy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM