Java- Manually sort a string array using compareTo() method

compareto java
java sort strings alphabetically
how to override compareto method in java for string
java sort string characters alphabetically
sort string array java
sort string lexicographically java
arrays.sort comparator
java compare strings alphabetically

Let me first say that I know that there a better ways to sort where you might use something other than an array. This an assignment for class where the user can store strings in an array, delete, display, and sort them. I am completely lost to where to go from here. I am trying to use a bubble sort and everything works except whatever is the first entry in my array won't sort. I avoid null pointer exceptions through filtering out null values which is why my if statement is so long.

private void sortItems(String[] cargohold) {
    String temp;
    for (int i = 0; i < cargohold.length - 1; i++) {
        for (int j = 1; j < cargohold.length; j++) {
            if (cargohold[i] != null && cargohold[j] != null && (cargohold[i].compareTo(cargohold[j]) < 0)) {
                temp = cargohold[j];
                cargohold[j] = cargohold[i];
                cargohold[i] = temp;
            }   
        }
    }
}

I have tried a bunch of different ways of doing this and I can't find any good reason why this shouldn't work. I have looked through anything I could find on Stack Overflow as far as examples and no one is having the same issue I am.

To recap, I may have 5 strings, "Derp", "Herp", "Sam", "Alfred", "Bill" and this sort will give me: "Derp", "Alfred", "Bill", "Herp", "Sam". Thanks in advance for the guidance.


The line

if(cargohold[i] != null && cargohold[j] != null && (cargohold[i].compareTo(cargohold[j]) < 0))

should be

if(cargohold[j] != null && cargohold[j-1] != null && (cargohold[j].compareTo(cargohold[j-1]) < 0))

and the swapping should be done as:

temp = cargohold[j];
cargohold[j] = cargohold[j-1];
cargohold[j-1] = temp;

Remember that in bubblesort you compare adjacent elements, where as your code does not do that.

Flaw

There will be cases when i > j and i < j, but the swapping logic remains the same, and that is completely wrong.

Java Sort Arrays Examples (with Comparable and Comparator), Sorting an array of Objects The natural ordering is defined by implementation of the compareTo() method which determines how the current object (obj1) is compared to another (obj2) of the same type. The order is based on return value (an integer number, say x) of the compareTo() method: obj1 > obj2 if x > 0. compareTo is defined in interface java.lang.Comparable . Syntax: public int compareTo(String str) Parameter input : str – This method only accepts only one input String data type. Method Returns: This Java method returns an int datatype which is based on the lexicographical comparison between two strings.


Bubblesort algorithm with some optimizations:

private static void sortItems(String cargohold[]) {
    String temp;
    boolean wasSwap = true;
    for (int index1 = 0; index1 < cargohold.length - 1 && wasSwap; ++index1) {
        wasSwap = false;
        for (int index2 = 0; index2 < cargohold.length - index1 - 1; ++index2) {
            if (cargohold[index2].compareToIgnoreCase(cargohold[index2+1]) > 0) {
                temp = cargohold[index2];
                cargohold[index2] = cargohold[index2+1];
                cargohold[index2+1] = temp;
                wasSwap = true;
            }
        }
    }
}

Average complexity being O(n^2) with the best case of O(n).

String compareTo() Method in Java with Example, compareTo() method is used to perform natural sorting on string. Natural sorting means the sort order which applies on the object, e.g., lexical� To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.


Your implementation is wrong.

Here is bubble sort (in a java-like shorthand):

for (index1 = 0; index1 < array.length - 1; ++index1)
    for (index2 = index1 + 1; index2 < array.length; ++index2)
        if (array[index1] < array[index1])
            swap(array[index1], array[index2]);

note the index2 = index1 + 1 of the inner loop.

Sort a String in Java (2 different ways), Apply toCharArray() method on input string to create a char array for input string. Use String class constructor to create a sorted string from char array. For this, we must have to implement compare() method based on our� So far we have gone through examples of sorting arrays using various variants of the java.util.Arrays.sort() method, including usages of the Comparable and Comparator. interfaces. Key points to remember are: The Comparable interface imposes the natural ordering of an object, through contract of the compareTo() method.


String[] str = { "red", "blue", "green" };
int n = str.length;
String temp;
System.out.println("Original String Array = " + Arrays.toString(str));
for(int a=0;a<n;a++) {
    for(int b=a+1;b<n;b++) {
        if( str[a].compareTo(str[b]) > 0 ) {
            temp = str[a];
            str[a] = str[b];
            str[b] = temp;
        }
    }
}
System.out.println("Sorted String Array = " + Arrays.toString(str));

7 Examples to Sort An Array in Java, Sorting String Array in Java - Ascending and Descending Order When you sort an array of String using sort() method, it sorts an array into compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array. 2. Using String.compareTo() We are going to write a program that will work to ask for the number of strings, application user wants to sort. Then user need to enter each string one at a time and press ENTER after each input. To compare two strings, String.compareTo() method has been used which compare two strings lexicographically.


Beginning Java - Unit 6 Arrays - Alphabetic Sorting, Sorting into alphabetic order can be accomplished with both the bubble and exchange Java provides two methods for comparing strings: compareTo and� The toCharArray() method of this class converts the String to a character array and returns it. To sort a string value alphabetically − Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class.


Sorting in Java, Let's start by sorting integer arrays first using Arrays.sort() method. We'll define the following int arrays in a @� The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0. It compares strings on the basis of Unicode value of each character in the strings. If first string is lexicographically greater than second string, it returns positive number (difference of


Different Approaches to Sorting Elements of an ArrayList in Java , Consider an ArrayList that stores country names as String objects. To sort The Collections.sort() method sorts ArrayList elements or elements of any other List Comparable is an interface with a single compareTo() method. Java String compareTo() method compares two strings lexicographically. We can consider it dictionary based comparison. 1. String comparison. If a string 'str1' comes before another string 'str2' in dictionary, then str2 is said to be greater than 'str1' in string comparison.