Bubble sort algorithm compares the adjacent elements in an array and swaps them if they're in the wrong order. To implement BubbleSort in Java, you need to make use of two nested for loop, you do not additional memory as we save the sorted data in the same array.
package org.code2care.java.sorting.algo;
import java.util.Arrays;
/**
* BubbleSort Example in Java
*
* Author: Code2care.org
* Date: 28 April 2023
* Version: v 1.0
*
*/
public class BubbleSortJavaExample {
public static void main(String[] args) {
//Unsorted Array
int[] unsortedArray = {4, 99, 2, 11, 34, 67, 54, 12, 45, 245, 234, 12, 200};
BubbleSortJavaExample bubbleSort = new BubbleSortJavaExample();
//Note: new array or Arrays.toString is not needed - added just for clarity
int[] sortedArray = bubbleSort.bubbleSortAlgorithm(unsortedArray);
System.out.println(Arrays.toString(sortedArray));
}
/**
*
* @param arrayOfNumbers: unsorted array as provided to sort
* @return: sorted array using bubble sort
*/
public int[] bubbleSortAlgorithm(int[] arrayOfNumbers) {
int arrayLength = arrayOfNumbers.length;
int tempVariable = 0;
for (int outerIndex = 0; outerIndex < arrayLength - 1; outerIndex++) {
for (int innerIndex = 0; innerIndex < arrayLength - outerIndex - 1; innerIndex++) {
int elementN = arrayOfNumbers[innerIndex];
int elementNPlus1 = arrayOfNumbers[innerIndex + 1];
if (elementN > elementNPlus1) {
tempVariable = arrayOfNumbers[innerIndex];
arrayOfNumbers[innerIndex] = arrayOfNumbers[innerIndex + 1];
arrayOfNumbers[innerIndex + 1] = tempVariable;
}
}
}
return arrayOfNumbers;
}
}
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!