Last active
July 26, 2018 13:33
-
-
Save m-x-k/d0314821cf5caf53f840d1f268e51d73 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 static Random random = new Random(); | |
private Integer[] sort(Integer[] array, Predicate<Integer> sortType) { | |
int count = 0; | |
boolean sorted = false; | |
int temp; | |
while (!sorted) { | |
sorted = true; | |
count++; | |
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; | |
} | |
} | |
} | |
// System.out.println("Iterations: " + count); | |
return array; | |
} | |
public static void main(String[] args) { | |
System.out.println("Bubble sort"); | |
Integer[] array = randomArray(100); | |
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))); | |
} | |
private static Integer[] randomArray(int i) { | |
Integer[] integers = new Integer[i]; | |
for (int j = 0; j < integers.length; j++) { | |
integers[j] = random.nextInt(100); | |
} | |
return integers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment