Search code examples
javaalgorithmsortingarraylistinsertion

Insertion sort Java algorithm in an arraylist String


So I have an arraylist that I want that I need to sort with an insertion sort algorithm for a programming class. I have this and ArrayList containing these String's = (Andrew, Felip, Juan, Camil, Jhon, William) and I have this Java code:

public void insertionSort( )
    {

        ArrayList<Reserve> array = giveReserves();

        for(int i = 1   ; i < array.size()-1; i++)
        {
            Reserve element = array.get(i);
            String nomI = element.giveNameClient();
            int j = i;
            String nomJM = array.get(j-1).giveNameClient();
            String nomJ = array.get(j).giveNameClient();
            while(j > 0 && (nomJM.compareTo(nomJ) > 0))
            {
                Reserve temp = array.get(j);
                array.set(j, array.get(j-1));
                array.set(j-1, temp);
                j = j-1;
            }
        }
    }

So I have an hotel that has an ArrayList of reserve's, each reserve has the name of the client that did it. What I want to do, is to sort the Reserve ArrayList by client name.

So I have a method that prints each name client, like this:

public void showNames()
    {
        for(Reserve x: reserves)
        {
            System.out.print(x.giveNameClient() +" ");
        }
    }

in the main() method I print the names of the clients before sorting and then sorted. btw the arraylist of reserves is in a class named Test.

public static void main(String args[])
    {
        Test object = new Test();
        System.out.println("Names: ");
        object.showNames();
        object.insertionSort();
        System.out.println();
        System.out.println("after sorting: ");
        object.showNames();
    }

Now when I compile this I get the following:

Names:
Juan Jhon Camil William Andrew Felip
after sorting: 
Andrew Camil Jhon Juan William Felip

The thing is that the output should be Andrew Camil Felip Jhon Juan William

Thanks.


Solution

  • This should give you your desired output. There are numerous issues in your code. You're skipping elements in the array with your i < array.size() - 1 loop definition.

    String[] inputArray = {"Juan", "Jhon", "Camil", "William", "Andrew", "Felip"};
    for(int i = 1; i < inputArray.length; i++)  {
        String key = inputArray[i];
        int j = i - 1;
    
        while (j >= 0 && key.compareTo(inputArray[j]) < 0) {
            inputArray[j + 1] = inputArray[j];
            j--;
        }
        inputArray[j + 1] = key;
    }
    System.out.println(Arrays.toString(inputArray));