Home > Software design >  How could I get this Insertion Sort code in alphabetical order?
How could I get this Insertion Sort code in alphabetical order?

Time:01-20

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;
}

}

CodePudding user response:

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]

CodePudding user response:

you can sort the hole array at once using static method Arrays.sort(arr)

import java.util.Arrays;
...

String[] arrayOfStrs = {"d","a","ca"};

Arrays.sort(arrayOfStrs);

// arrayOfStrs is now ["a","ca","d"]

CodePudding user response:

To sort it from less to more amount of letrers create first a Comparator class that uses the String length:

public class StringLengthComparator implements Comparator<String> {
  public int compare(String o1, String o2) {
    return Integer.compare(o1.length(), o2.length());
  }
}

And then use it in the Arrays.sort(...) method:

Arrays.sort(a, new StringLengthComparator());

To sort them alphabetically you just need this:

Arrays.sort(a);
  •  Tags:  
  • Related