0

I'm new to java and I recently wrote a program that sorts an array of strings in import java.util.Scanner;

 public class 
9
  • You could simply compare the substring(1, 4) or the two strings. And you could use Arrays.sort(), passing a Comparator, instead of implementing your own sorting algorithm. Commented Feb 17, 2016 at 8:26
  • you dont have to take care of comparing with charAt index, compareTo method do it internally, means internally two string will be compared at index 1, 2,.. upto String length Commented Feb 17, 2016 at 8:26
  • What have you tried? What other searches did you look? Do you want to implement this yourself or use a library? Commented Feb 17, 2016 at 8:27
  • @Vishrant I would prefer using CharAt. Commented Feb 17, 2016 at 8:36
  • @JB I have no idea what a comparator is Commented Feb 17, 2016 at 8:40

2 Answers 2

4

You can still use Arrays.sort method for this and just provide own customized Comparator:

Arrays.sort(name,
    (String left, String right) ->
        left.substring(1).compareTo(right.substring(1))
);

If you want to implement this on your own, note that comparator is supposed to return 0 if the paramaters are equal, negative number if the left is lower and positive number if the right is lower. So the comparator character by characters will look like:

Arrays.sort(name,
    (String left, String right) -> {
        // starting from index 1 and going until reaching end of strings
        for (int i = 1; i < left.length() && i < right.length(); ++i) {
            int diff = left.charAt(i)-right.charAt(i);
            if (diff != 0)
                return diff;
        }
        // if strings are equal so far, return that the lower is the shorter one
        return left.length()-right.length();
    }
);
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks but that looks pretty complicated..I'm trying to understand how to use things like CharAt to solve this..
@ZbynekVyskovsky-kvr000 Please mention java version 1.8 or later for using lambda expression
@KidKool , You could also follow this answer stackoverflow.com/questions/35402555/…
@KidKool, The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them. ref-tutorialspoint.com/java/java_collections.htm AND where you need trim()?
@KidKool : It definitely isn't. You can write your own sort implementation but frankly why to reinvent the wheel. So I suggested existing implementation which is part of core java. However, moving the comparator body to separate method isn't big deal I believe.
|
0

Since you have already implemented the user input and displaying the values, I won't take that into consideration.

There are two things that need to be implemented:

  1. Comparing two objects with eachother;
  2. Based on the result of the comparison, insert one of the items either before or after the element.

These are two separate functions.

Comparing two objects with eachother

Take a look at the Comparator<T> interface. It lets you implement the way how objects are compared. The one and only method of the Comparator interface is the method compare(String o1, String o2). You only need to make sure that:

  • if both objects should have the same order, return 0. In our example below, Saab and Jaguar are the same, because we're trying to order only by the second character, which is an a for both.
  • if o1 is 'less' than o2, return -1. In our example, comparing Saab with Opel would return -1, because the a is 'less' than the p.
  • if o1 is 'greater' than o2, return 1. In our example, comparing Skoda with Jaguar would return 1, because the second character of Skoda (the k) is 'greater' than the second character of Jaguar (the a).

By the way, in your original code, you used the method String.compareTo(), which is almost exactly the same as the Comparator<String>.compare(String, String) method.

class MyCustomComparator implements Comparator<String>() {

    @Override
    public int compare(String t, String t1) {
        // We assume that the strings are not null
        // We also assume that the length of the
        // strings is at least 2.
        if (t.charAt(1) < t1.charAt(1)) {
            return -1;
        }
        else if (t.charAt(1) > t1.charAt(1)) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

Inserting the elements at the right spots

Once you have defined your own Comparator, the only thing you have to do is pass it to the method Arrays.sort(T[] a, Comparator<? super T> c), which accepts as first argument your array with the strings, and as second argument your own defined Comparator.

Example:

String[] array = new String[] {
    "Saab",
    "Opel",
    "Skoda",
    "Jaguar",
    "Chevrolet"
};
// Result when ordering by second char:
// Saab, Jaguar, Chevy, Skoda, Opel

// Sort the array
Arrays.sort(array, new MyCustomComparator());

And if you really, really, really want to avoid the Arrays.sort() method, you can just reinvent the wheel:

/** Returns a new string array with the elements sorted */
String[] sort(String[] strings, Comparator<String> c) {
    List<String> sortedArray = new ArrayList<String>();
    for (String str : strings) {
        int i;
        for (i = 0; i < sortedArray.size(); i++) {
            if (c.compare(str, sortedArray.get(i)) < 0) {
                sortedArray.add(i, str);
                break;
            }
        }
        if (i == sortedArray.size()) {
            sortedArray.add(strings[i]);
        }
    }
    return sortedArray.toArray(new String[0]);
}

Alternatively, you can use your original code with these modifications:

void myCustomCompareTo(String s1, String s2) {
    if (s1.charAt(1) < s2.charAt(1)) {
        return -1;
    }
    else if (s1.charAt(1) > s2.charAt(2)) {
        return 1;
    }
    else { // They're equal
        return 0;
    }
}

String[] sortMe(String[] strs) {
    for (int i = 0; i < 5 - 1; i++) {
        for (int j = 0; j < 5 - 1 - i; j++) {
            if (strs[j].myCustomCompareTo(name[j + 1]) > 0) {
                // Swap the two values
                String temp = name[j];
                strs[j] = strs[j + 1];
                strs[j + 1] = temp;
            }
        }
    }
    return strs;
}

Other notes

  • I see you have a hard time understanding the code of the given answers. I suggest you start examining the String class. You will read about the length() and the charAt(int) method. Especially length() is used often; I suggest you take that into account. Also, learning Generics might also help.
  • Almost every programmer I know is using the variable i in a for loop, instead of x. You should consider doing so too.
  • You are not using the variable num.
  • The arrows (->) Zbynek Vyskovsky - kvr000 is using, are part of lambda expressions. Lambda expressions are syntactic sugar, they make things easier to express (but not necessarily to read, especially for newcomers in the Java field).

    For instance,

    Arrays.sort(name,
        (String left, String right) ->
            left.substring(1).compareTo(right.substring(1))
    );
    

    is exactly the same as this:

    Arrays.sort(name, new Comparator() {
    
        @Override
        public int compare(String left, String right) {
            return left.substring(1).compareTo(right.substring(1));
        }
    );
    

    But in fact, this is beyond the scope of this.

9 Comments

I don't get it..That program doesn't get user inputed strings. Does that program even display the sorted list of strings after they are sorted? I am so confused..
Do I have to use arrays.sort or is there a more basic way? Im just trying to learn everything I can...Thanks for your help..The edited post was great.
I edited my code but is there a way to do this using charAt but WITHOUT using arrays.sory or lambdas?
@KidKool That is possible. I'm going to update my answer. But ... why should you not use Arrays.sort()?
I just want to see if I can do this without using that library..It seems a little to advanced for me...I wanna break this down in a really basic way...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.