Search code examples
javabubble-sort

Bubble Sort method swapping


My assignment requires me to code several methods that will compare an array of first names from a .txt file.

I'm currently stuck on a BubbleSort method. Trying to get it to run.

This is my code for the BubbleSort:

 public static int bubbleSort(String[] array) {
    boolean swapped = false;
    int compNumber = 0;
    int length = length.array;
    while (swapped = false) {
      for (int i = 0; i < length.array-1; i++) {
        if (array[i-1] > array[i]) {
          String temp = 
          array[i-1] = array[i];
          swapped = true;
        }
      }
    }
    return compNumber;
  }

I don't believe I'm swapping correctly because I'm not sure how to use the temp variable (hence it being blank).

Could someone take a look at this and point me in the right direction?

Thanks very much in advance!


Solution

  • Not sure if your algorithm is correct, but here is the standard way to swap. If you're sorting a String array you will also need to get the numerical value (I assume the Strings contain numbers?). Also just noticed you will get an array out of bounds exception, start at 1 if you are looking at index i-1. One more thing, i < length.array-1 should be i < array.length

    And one more thing as well, the loop should continue until no swaps were made, so it should be while (swapped == true), and re-set it to false in each iteration.

        public static void bubbleSort(String[] array) {
        boolean swapped = true;
        int compNumber = 0;
        int length = length.array;
        while (swapped == true) { //note the ==
          swapped = false;
          for (int i = 1; i < array.length; i++) {
            compNumber++;
            if (Integer.parseInt(array[i-1]) > Integer.parseInt(array[i])) {
              String temp = array[i-1]
              array[i-1] = array[i];
              array[i] = temp;
              swapped = true;
            }
          }
        }
        return compNumber; 
      }