Search code examples
javabubble-sortselection-sort

Is my bubble sort and selection sort properly implemented?


Here is what I have for the bubble sort algorithm.

public void bubbleSort(int[] arr) {
  boolean swapped = true;
  int j = 0;
  temp = 0;

while(swapped) {
  swapped = false;
  j++;

for(int i = 0; i < arr.length; i++) {
  if (arr[i] > arr[i + 1]) {
    temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    swapped = true;
  }
 }
}
}

And for selection sort:

public int[] selectionSort(int[] arr) {
  int i = 0;
  int j = 0;
  int minValue = 0;
  int minIndex = 0;
  int temp = 0;

for(i = 0; i < arr.length - j; j++) {
   minValue = arr[i];
   minIndex = i;

for(j = i; i < arr.length; j++) {
  if (minValue < arr[i]) {
    minValue = arr[j];
    minIndex = j;
  }
}

if (minValue < arr[i]) {
   temp = arr[i];
   arr[i] = arr[i + 1];
   arr[i + 1] = temp;
}
}
return arr;
}

Not sure about these implementations. When I add a System.out.println(arr[i]); in there the numbers for bubble sort come out as: 4 3 2 1 3 2 1 2 1 1 [I@6d06d69c

When put at after the first if statement.

Now when I create a System.out.println(arr[i]); for selection sort it comes out as: 1 2 3 4 5 [I@6d06d69c

When put after the second if statement.

Thank you


Solution

  • There are a few bugs in your implementations which I have tried to correct.

    public void bubbleSort(int[] arr) {
      boolean swapped = true;
      int j = 0;
      temp = 0;
    
    while(swapped) {
      swapped = false;
      j++;
    
    for(int i = 0; i < arr.length-j; i++) {
      if (arr[i] > arr[i + 1]) {
        temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;
        swapped = true;
      }
     }
    }
    }
    
    public int[] selectionSort(int[] arr) {
      int i = 0;
      int j = 0;
      int minValue = 0;
      int minIndex = 0;
      int temp = 0;
    
    for(i = 0; i < arr.length - 1; i++) {
       minValue = arr[i];
       minIndex = i;
    
    for(j = i+1; j < arr.length; j++) {
      if (minValue < arr[j]) {
        minValue = arr[j];
        minIndex = j;
      }
    }
    
    if (minValue < arr[i]) {
       temp = arr[i];
       arr[i] = minValue;
       arr[minIndex] = temp;
    }
    }
    return arr;
    }