package sorting;
import java.util.*;
public class QuickSort {
private static List<Integer> sort(List<Integer> data) {
if (data.size() < 2){
return data;
}
List<Integer> lower = new LinkedList<Integer>();
List<Integer> higher = new LinkedList<Integer>();
int pivot = data.get(0);
for (int i = 1; i < data.size(); i++) {
if (data.get(i) < pivot) {
lower.add(data.get(i));
} else {
higher.add(data.get(i));
}
}
sort(lower);
sort(higher);
lower.add(pivot);
lower.addAll(higher);
return lower;
}
public static void main(String[] args) {
List<Integer> unsortedData = new ArrayList<Integer>();
int size = new Random().nextInt(100);
for (int i = 0; i < size; i++) {
unsortedData.add(new Random().nextInt(65536) - 32768);
}
printSort("Unsorted data :", unsortedData);
printSort("Sorted data :", sort(unsortedData));
}
private static void printSort(String message, List<Integer> data) {
System.out.println(message);
for (int item : data) {
System.out.print(item + " ");
}
System.out.println("\n");
}
}
Sunday, January 21, 2018
Quick Sort
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment