Skip to content

Instantly share code, notes, and snippets.

@PPartisan
Created April 14, 2016 18:33
Show Gist options
  • Save PPartisan/0da9792be6a0327c61dc05ad02f791d3 to your computer and use it in GitHub Desktop.
Save PPartisan/0da9792be6a0327c61dc05ad02f791d3 to your computer and use it in GitHub Desktop.
Someone asked me to make a "Bubble Sort" algorithm. So...
import java.util.*;
import java.lang.*;
import java.io.*;
class WhatsAbubbleSort {
public static void main (String[] args) throws java.lang.Exception {
final int[] unsorted = new int[] { 23, 25, 7, 13, 94, 11 };
WhatsAbubbleSort sorter = new WhatsAbubblerSort();
final int[] sorted = sorter.runBubbleSort(unsorted);
WhatsAbubbleSort.printArray(sorted);
}
int[] runBubbleSort(int[] numbers) {
final int[] output = numbers.clone();
while(!bubbleSort(output));
return output;
}
public static void printArray(int[] numbers) {
for (int number : numbers) {
System.out.println(String.valueOf(number));
}
}
private boolean bubbleSort (int[] numbers) {
final int limit = numbers.length;
for (int i = 0; i < limit; i++) {
if ((i+1 < limit) && (isMoveRequired(numbers[i], numbers[i+1]))) {
int temp = numbers[i+1];
numbers[i+1] = numbers[i];
numbers[i] = temp;
return false;
}
}
return true;
}
private boolean isMoveRequired(int i1, int i2) {
return i2 > i1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment