Created
March 22, 2018 20:07
-
-
Save RobertronS/1ff60153a34f25727722cb2148c35967 to your computer and use it in GitHub Desktop.
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.*; | |
public class QuickSort <T extends Comparable<T>>{ | |
public void swap(ArrayList<T> array, T value1, T value2){ | |
Collections.swap(array, array.indexOf(value1),array.indexOf(value2)); | |
} | |
public void quickSort(ArrayList<T> arrayList){ | |
int low = 0; | |
int high = arrayList.size()-1; | |
quick(arrayList, low, high); | |
} | |
public void quick(ArrayList<T> arrayList, int low, int high){ | |
if (low < high){ | |
int p = partition(arrayList, low, high); | |
quick(arrayList, low, p-1); | |
quick(arrayList, p+1, high); | |
} | |
} | |
public int partition(ArrayList<T> arrayList, int lower, int high){ | |
T pivot = arrayList.get(high); | |
int partition = lower; | |
for (int i = lower; i < high; i++){ | |
if (arrayList.get(i).compareTo(pivot) < 0){ | |
swap(arrayList, arrayList.get(i), arrayList.get(partition)); | |
partition = partition + 1; | |
} | |
} | |
swap(arrayList, arrayList.get(partition), arrayList.get(high)); | |
return partition; | |
} | |
public static void main(String[] args) { | |
QuickSort<Integer> quickSort = new QuickSort<>(); | |
Scanner scanner = new Scanner(System.in); | |
System.out.println("what is your number?"); | |
int size = scanner.nextInt(); | |
ArrayList<Integer> arrayList = new ArrayList<>(); | |
for (int i = 0; i < size; i++){ | |
arrayList.add(i, (int)(Math.random()*200)); | |
} | |
System.out.println(Arrays.toString(arrayList.toArray())); | |
quickSort.quickSort(arrayList); | |
/*Collections.sort(arrayList, new Comparator<Integer>() { | |
@Override | |
public int compare(Integer o1, Integer o2) { | |
if (o1 == o2){ | |
return 0; | |
} | |
return o1 > o2 ? 1: -1; | |
} | |
});*/ | |
System.out.println(arrayList.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment