快速排序

本文介绍了一种基于划分算法的快速排序方法,并提供了一个具体的Java实现案例。该算法通过选取中心值进行一趟排序,将数组分为左右两部分,再递归地对这两部分进行排序,直至整个数组有序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速排序是建立在划分算法的基础之上的,在要排的数(比如数组A)中选择一个中心值key(比如A[0]),通过一趟排序将数组A分成两部分,其中以key为中心,key右边都比key大,key左边的都key小,然后对这两部分分别重复这个过程,直到整个有序。

      
package algorithm;

public class QuickSort {


public static void main(String[] args) {
int maxSize=16;
ArrayIns arr=new ArrayIns(maxSize);
for(int i=0;i<16;i++){
arr.insert((int)(Math.random()*99));
}
arr.display();
System.out.println("sort");
arr.quickSort();
arr.display();
}

static class ArrayIns{

private long[] theArray;
private int nElems;

public ArrayIns(int max){
theArray=new long[max];
nElems=0;
}
public void insert(long value){
theArray[nElems]=value;
nElems++;
}
public void display(){
for(int i=0;i<nElems-1;i++){
System.out.println("i----"+theArray[i]);
}
}
public int size(){
return nElems;
}

public void quickSort(){
reQuickSort(0,nElems-1);
}

public void reQuickSort(int left,int right){
if(right-left<=0){
return;
}else{
long pivot=theArray[right];
int patitionIt = patitionIt(left, right, pivot);
reQuickSort(left,patitionIt-1);
reQuickSort(patitionIt+1,right);
}
}

/**
*
* @param left
* @param right
* @param pivot
* @return
*/
public int patitionIt(int left,int right,long pivot) {
int leftPtr = left ;
int rightPtr = right-1 ;
while (true) {
while ( theArray[leftPtr] < pivot) {
++leftPtr;
}
while (rightPtr>leftPtr&&theArray[rightPtr] > pivot) {
--rightPtr;
}
if (leftPtr >= rightPtr) {
break;
} else {
swap(leftPtr,rightPtr);
}
}
swap(leftPtr,right);
return leftPtr;
}
public void swap(int index1,int index2){
long temp;
temp=theArray[index1];
theArray[index1]=theArray[index2];
theArray[index2]=temp;
}
}
}

转载于:https://www.cnblogs.com/liwei2018/p/8975177.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值