3

I have an issue with my method when I try to sort :

Here's what my code look like :

public void sort() 
{
  boolean found=true;
  int i = 0;
  String temp;
  while(found)
  {
    found = false;

    for ( i = 0; i<cars.length-1; i++)
    {
      if (cars[i].compareToIgnoreCase(cars[i+1])> 0)
      {

I got this far but still not sure on how to sort them ?

1
  • any reason why you don't use the sort() function?
    – Red Alert
    Commented Nov 27, 2013 at 20:55

5 Answers 5

2

Try

Arrays.sort(cars);

if cars are non-standard type then write your own Comparator (lets name it comp) and do:

Arrays.sort(cars, comp);

Here's documentation of Comparator interface.

Update Or, just implement Comparable interface to class of cars, as Mr. Polywhirl said below.

0
2

You already initialized temp, just move cars[i] to temp and then cars[i+1] to cars[i] then temp to cars[i+1], then found =true to leave loop translate this to code

1

How about using a built-in method? Arrays.sort() will work just fine.

1

What way do you want this data sorted? Also I am assuming you want to do this manually? If not, then use Java's built in Arrays.sort() method as mentioned above.

1

Here is a complete implementation of the bubble sort algorithm in Java from Rosetta Code:

public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
    boolean changed = false;
    do {
        changed = false;
        for (int a = 0; a < comparable.length - 1; a++) {
            if (comparable[a].compareTo(comparable[a + 1]) > 0) {
                E tmp = comparable[a];
                comparable[a] = comparable[a + 1];
                comparable[a + 1] = tmp;
                changed = true;
            }
        }
    } while (changed);
}

Since you're probably doing this for a class, you should try to understand what is happening. Use lots of System.out.println() statements to show how your program ran.

You should also find out how to use the debugger on your IDE. It will allow you to see how the program runs line by line, and how the data changes.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.