package sort;
import java.util.Random;
public class QuickSort {
private int[] input;
private int partition(int[] input,int p,int r){
int x = input[r];
int i = p -1;
for(int j = p; j< r;j++){
if(input[j] <= x){
i++;
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
int temp = input[i+1];
input[i+1] = input[r];
input[r] = temp;
return i + 1;
}
public void out(){
for(int i = 0;i< input.length; i++){
System.out.print(input[i] + " ");
}
System.out.println();
}
public QuickSort(int[] input){
this.input = input;
}
public void quickSort(){
sort(input,0,input.length -1 );
}
private void sort(int[] input,int p,int r){
if(p<r){
int q = partition(input, p, r);
sort(input, p, q-1);
sort(input, q+1, r);
}
}
public int randomPartition(int[] input,int p,int r){
int i = random(p, r);
int temp = input[i];
input[i] = input[r];
input[r] = temp;
return partition(input, p, r);
}
public void randomQuickSort(){
randomQuickSort(input, 0, input.length -1);
}
private void randomQuickSort(int[] input,int p,int r){
if(p < r){
int q = randomPartition(input, p, r);
randomQuickSort(input, p, q-1);
randomQuickSort(input, q+1, r);
}
}
public static int random(int p,int r){
return new Random().nextInt(r + 1 -p) + p;
}
private int hoarePartition(int input[],int p,int r){
int x = input[p];
int i = p;
int j = r;
while(true){
while(input[j] > x){
j-- ;
}
while(input[i] < x){
i++ ;
}
if(i < j){
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
else{
return j;
}
}
}
private void hoareSort(int input[],int p,int r){
if(p < r){
int q = hoarePartition(input, p, r);
hoareSort(input, p, q -1);
hoareSort(input, q +1, r);
}
}
public void hoareSort(){
hoareSort(input, 0, input.length -1);
}
public static void main(String[] args){
int[] input = {2,8,7,1,3,5,6,4};
for(int j = 0; j < input.length;j++){
System.out.print(input[j] + " ");
}
System.out.println();
QuickSort sort = new QuickSort(input);
// sort.quickSort();
// sort.randomQuickSort();
sort.hoareSort();
sort.out();
}
}
排序算法(二)
最新推荐文章于 2024-09-10 12:55:35 发布