-
-
Save yuri-adeodato/be9ede889d1bb6975451952981ad7352 to your computer and use it in GitHub Desktop.
Java 8 bubble sort integer array example using predicates for acending and descending options
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.Arrays; | |
import java.util.Random; | |
import java.util.function.Predicate; | |
public class BubbleSort { | |
private int[] sort(int[] array, Predicate<Integer> sortType) { | |
boolean sorted = false; | |
int temp; | |
while (!sorted) { | |
sorted = true; | |
for (int i = 0; i < array.length - 1; i++) { | |
if (sortType.test(i)) { | |
temp = array[i]; | |
array[i] = array[i + 1]; | |
array[i + 1] = temp; | |
sorted = false; | |
} | |
} | |
} | |
return array; | |
} | |
public static void main(String[] args) { | |
System.out.println("Bubble sort"); | |
int[] array = new Random().ints(100, 0, 1000).toArray(); | |
System.out.println("Original: " + Arrays.toString(array)); | |
BubbleSort b = new BubbleSort(); | |
Predicate<Integer> ascending = i -> array[i] > array[i + 1]; | |
System.out.println("Ascending: " + Arrays.toString(b.sort(array, ascending))); | |
Predicate<Integer> descending = i -> array[i] < array[i + 1]; | |
System.out.println("Descending: " + Arrays.toString(b.sort(array, descending))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment