简体   繁体   中英

How Do I Implement an Insertion Sort Method for A Generic ArrayList?

I am meant to create a simple insertion sort method which sorts a series of generic names into alphabetical order. This should be simple, and I have already reviewed many other examples of insertion sort online, including on this site, yet I still cannot seem to obtain the correct output despite comparing my code, line-by-line, with other versions and being unable to identify what I have done different than some supposedly successful insertion sort methods.

The following code is the main class which I am not meant to alter:

  public static void main(String[] args) {
    GenericTools t = new ToolBox();
    ArrayList<String> data = new ArrayList<>();
    data.add("Carlos");
    data.add("Alice");
    data.add("Bob");
    data.add("Zebra");
    data.add("Fred");

    t.insertionSort(data);
    data.forEach(x -> System.out.println(x));
}

And, this is the GenericTools interface referenced above, for the record:

public <T> void swap(ArrayList<T> data, int p1, int p2);

Finally, this is my code which should be correctly sorting this list:

@Override
    public <T extends Comparable<T>> void insertionSort(ArrayList<T> data) {
        int i, x =0;
        T key;
        for (i=1;i<data.size();i++){
            key= data.get(i);
            while (x>=0 && data.get(x).compareTo(key) > 0){
                data.set(x+1,data.get(i));
                x--;
            }
            data.set(x+1,key);
        }
      }

However, instead produces the following output:

Fred
Alice
Bob
Zebra
Fred

As opposed to correct output of:

Alice
Bob
Carlos
Fred
Zebra

So you intended to iterate over the sorted part (indices between 0 and i - 1) of the ArrayList in descending order and shift elements relatively greater than key in right direction by one position at the same time, and find the correct position where to put the key (data.get(i)). Your algorithm is right, but there are two simple mistakes you've made there:

  1. you forgot to initialize variable x to i - 1 before inner while-loop.

  2. when current element is alphabetically greater than the key , you should move current element (data.get(x)) one step right instead of data.get(i) .

    @Override
    public <T extends Comparable<T>> void insertionSort(ArrayList<T> data) {
        int i, x =0;
        T key;
        for (i=1; i<data.size(); i++){
            key= data.get(i);
            x = i - 1; // set x to i - 1
            while (x >= 0 && data.get(x).compareTo(key) > 0){
                data.set(x+1, data.get(x)); // move data.get(x) instead of data.get(i).
                x--;
            }
            data.set(x+1,key);
        }
    }

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