使用Java8编程风格写的快速排序:
1、使用数组的版本:
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Java8QuickSort {
public static void main(String[] args) {
Java8QuickSort quickSort = new Java8QuickSort();
int[] initialArray = {2, 1, 3, 5, 6, 6, 7, 7, 7, 454, 321, 3, 3, 2,};
int [] sortedArray = quickSort.sort(initialArray);
System.out.println(Arrays.toString(sortedArray));
}
private int[] sort(int[] initialArray) {
if(initialArray.length <= 1) {
return initialArray;
}
int pivotIndex = initialArray.length / 2;
int[] smaller = IntStream.of(initialArray).filter(value -> value < initialArray[pivotIndex]).toArray();
int[] equal = IntStream.of(initialArray).filter(value -> value == initialArray[pivotIndex]).toArray();
int[] bigger = IntStream.of(initialArray).filter(value -> value > initialArray[pivotIndex]).toArray();
return Stream.of(IntStream.of(sort(smaller)), IntStream.of(equal), IntStream.of(sort(bigger)))
.reduce(IntStream.empty(), IntStream::concat).toArray();
}
}
2、使用容器的版本:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8QuickSort2 {
public static void main(String[] args) {
Java8QuickSort2 quickSort = new Java8QuickSort2();
List<Integer> initialData = List.of(2, 1, 3, 5, 6, 6, 7, 7, 7, 454, 321, 3, 3, 2);
List<Integer> sortedData = quickSort.sort(initialData);
System.out.println(sortedData);
}
private <T extends Comparable<T>> List<T> sort(List<T> initialData) {
if (initialData.size() <= 1) {
return initialData;
}
int pivotIndex = initialData.size() / 2;
List<T> smaller = initialData.stream().filter(t -> t.compareTo(initialData.get(pivotIndex)) < 0).collect(Collectors.toList());
List<T> equal = initialData.stream().filter(t -> t.compareTo(initialData.get(pivotIndex)) == 0).collect(Collectors.toList());
List<T> bigger = initialData.stream().filter(t -> t.compareTo(initialData.get(pivotIndex)) > 0).collect(Collectors.toList());
return Stream.of(sort(smaller), equal, sort(bigger))
.reduce(Collections.emptyList(), (left, right) -> {
List<T> result = new ArrayList<>();
result.addAll(left);
result.addAll(right);
return result;
});
}
}
网友评论