简体   繁体   中英

Sorting ArrayList With same Algo as Array

I am trying to sort an ArrayList by implementing a similar algorithm I have used to sort arrays. I know I can use Collects.sort but as I am still a beginner I would rather write the code and learn it. compare the value of two integer objects stored in an array list. This is my code with the scores array being passed as an argument via reference to this method. Right now this code is not sorting properly but rather inserting the lowest number in the array at all subscripts. On a side note I was curious how I could compare the scores at index j and index smallest with the compareTo() method as I am comparing objects not primitives I feel it would be a better solution than casting. Thank you!

        int smallest;
    for (int i = 0; i < 5; i++)
    {
        smallest = i;
        for (int j = i; j < scores.size(); j++)
        {
            if ((Integer) scores.get(j) < (Integer) scores.get(smallest))
                smallest = j;
        }

        int temp = (Integer) scores.get(i);
        int swap = (Integer) scores.get(smallest); 
        scores.add(i, swap);
        scores.add(smallest, temp);

    }

Right now this code is not sorting properly but rather inserting the lowest number in the array at all subscripts.

You need to use set() method instead of add() to replace the elements.

On a side note I was curious how I could compare the scores at index j and index smallest with the compareTo() method as I am comparing objects not primitives I feel it would be a better solution than casting

You can avoid casting easily by specifying explit type for your collection, like new ArrayList<Integer> .

Gathering all together here's the corrected code:

    ArrayList<Integer> scores = new ArrayList<Integer>();
    scores.add(5);
    scores.add(4);
    scores.add(2);
    scores.add(1);
    scores.add(3);
    System.out.println(scores);
    int smallest;
    for (int i = 0; i < scores.size(); i++)
    {
        smallest = i;
        for (int j = i; j < scores.size(); j++)
        {
            if (scores.get(j) < scores.get(smallest))
                smallest = j;
        }

        int temp = scores.get(i);
        int swap = scores.get(smallest);
        scores.set(i, swap);
        scores.set(smallest, temp);

    }
    System.out.println(scores);

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