Example of quick sort in JAVA version
- 2020-05-27 05:26:59
- OfStack
The example of this article describes the implementation of JAVA quicksort. I will share it with you for your reference as follows:
package com.ethan.sort.java;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class QuickSort {
public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) {
if(arr.size()<=1) {
return arr;
}
E pivot = arr.get(0);
// Every recursion is initialized, every time list Don't 1 sample
List<E> less = new LinkedList<E>();
// pivot , This set is only 1 Each element is initialized every time, not at all 1 sample
List<E> pivotList = new LinkedList<E>();
List<E> more = new LinkedList<E>();
for(E i:arr){
if(i.compareTo(pivot)<0) {
less.add(i);
} else if(i.compareTo(pivot)>0) {
more.add(i);
} else {
pivotList.add(i);
//System.out.println("p---->"+i);
}
}
// recursive
less = quickSort(less);// than pivot small
// And for quicksort, right more, Divide it into two parts
more = quickSort(more);
// Joining together less pivot more
less.addAll(pivotList);
//pv-------->[23], In the end only 1 An element
System.out.println("pv-------->"+pivotList);
less.addAll(more);
return less;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] arr = {23,2,8,43,22,32,4,5,34};
List l = quickSort(Arrays.asList(arr));
Iterator i = l.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}
}
}
I hope this article has been helpful to you in java programming.