Skip to content

Instantly share code, notes, and snippets.

@RobertronS
Created March 21, 2018 19:41
Show Gist options
  • Save RobertronS/dfa9725ab8ae3bff3d2551f418261a84 to your computer and use it in GitHub Desktop.
Save RobertronS/dfa9725ab8ae3bff3d2551f418261a84 to your computer and use it in GitHub Desktop.
import java.util.*;
public class QuickSort <T extends Comparable<T>>{
public void swap(ArrayList<T> array, T value1, T value2){
T temp;
temp = value1;
array.set(array.indexOf(value1), value2);
array.set(array.indexOf(value2), temp);
}
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 j = lower; j < high; j++){
if (arrayList.get(j).compareTo(pivot) <= 0){
swap(arrayList, arrayList.get(partition), arrayList.get(j));
partition = partition + 1;
}
}
swap(arrayList, arrayList.get(partition), arrayList.get(partition));
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));
}*/
arrayList.add(45);
arrayList.add(20);
arrayList.add(50);
System.out.println(Arrays.toString(arrayList.toArray()));
//quickSort.swap(arrayList, 0, 2);
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