排序算法(二)


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();

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值