Created
April 14, 2016 18:33
-
-
Save PPartisan/0da9792be6a0327c61dc05ad02f791d3 to your computer and use it in GitHub Desktop.
Someone asked me to make a "Bubble Sort" algorithm. So...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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