Search code examples
javainsertion-sortalphabetical

How could I get this Insertion Sort code in alphabetical order?


I am new to coding and I put my code in order going from least amount of letters to greatest amount. Please help me understand how to put the code into alphabetical order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] a = new String[] {"bread", "milk", "cheese", "spinach", "apple", "peanuts"};
        System.out.println("Before Sort:" + Arrays.toString(a));
        insertionSort(a);
        System.out.println("After Sort: " + Arrays.toString(a));

        System.out.println();

        a = new String[] { "Allison", "Neha", "Charley", "Jason", "Tyson", "Miles", "Riley" };
        System.out.println("Before Sort:" + Arrays.toString(a));
        insertionSort(a);
        System.out.println("After Sort: " + Arrays.toString(a));


    }

    public static void insertionSort(String[] a) {
        // Move the marker from index 1 to the last index
        for (int i = 1; i < a.length; i++) {
            // Insert the element at the marker to the right position
            insert(a, i);

        }
    }
    public static void insert(String[] a, int marker) {
        String unsortedElement = a[marker];

        // shift other elements to the right to create the correct position
        int correctPosition = marker;
        for (int i = marker - 1; i >= 0; i--) {
            if (a[i].length() > unsortedElement.length()) {
                a[i + 1] = a[i];
                correctPosition--;
            }
            else {
                break; // stop looping
            }
        }
        // Insert the unsorted element to the correct position
        a[correctPosition] = unsortedElement;
    }
}

Solution

  • You have to change the condition inside the insert() method.

    Comparison of String objects could be done using method compareTo.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#compareTo(java.lang.String)

    Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.

    Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

    In other words, you may visualize what the method compareTo() does is like a 'weighting' of those strings using scales.

    If 'weights' are equal the compareTo() returns 0, if the first string is 'lighter' than the second (a string that is passed as an argument) a 'scales' (compareTo()) will give you a negative value.

    That's why the condition in the code below is written as

    unsortedElement.compareTo(a[i]) < 0

        public static void insert(String[] a, int marker) {
            String unsortedElement = a[marker];
    
            // shift other elements to the right to create the correct position
            int correctPosition = marker;
            for (int i = marker - 1; i >= 0; i--) {
                if (unsortedElement.compareTo(a[i]) < 0) {
                    a[i + 1] = a[i];
                    correctPosition--;
                }
                else {
                    break; // stop looping
                }
            }
            // Insert the unsorted element to the correct position
            a[correctPosition] = unsortedElement;
        }
    

    OUTPUT:

    Before Sort:[Allison, Neha, Charley, Jason, Tyson, Miles, Riley]
    After Sort: [Allison, Charley, Jason, Miles, Neha, Riley, Tyson]