快速排序-转自java数据结构与算法

来源:互联网 发布:淘宝导航条的尺寸 编辑:程序博客网 时间:2024/04/28 11:21
package cn.ccnu.lzc;import java.util.Random;public class QuickSort {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint maxSize=16;ArrayIns arr=new ArrayIns(maxSize);for(int i=0;i<maxSize;i++){int n=new Random().nextInt(100);arr.insert(n);}arr.display();arr.quickSort();arr.display();}}class ArrayIns{private int[] theArray;private int nElems;//初始化数组public ArrayIns(int max){this.theArray=new int[max];this.nElems=0;}//向数组中插入数据public void insert(int value){theArray[nElems++]=value;}//打印数组public void display(){for(int i:theArray){System.out.print(i+" ");}System.out.println();}//快速排序,选取数组最后一个为关键字public void quickSort(){recQuickSort(0,nElems-1);}public void recQuickSort(int left,int right){if(left>=right){return;}int pivot=theArray[right];int partition=partitionIt(left,right,pivot);recQuickSort(left,partition-1);recQuickSort(partition+1,right);}//求得最终关键字的位置private int partitionIt(int left,int right,int pivot){int leftptr=left-1;int rightptr=right;while(true){while(theArray[++leftptr]<pivot);//这里不需要进行越界检测,因为leftptr最后不可能越过关键字while(rightptr>0&&theArray[--rightptr]>pivot);if(leftptr>=rightptr){break;}else{swap(leftptr,rightptr);}}swap(leftptr,right);return leftptr;}private void swap(int leftptr, int rightptr) {// TODO Auto-generated method stubint temp=theArray[leftptr];theArray[leftptr]=theArray[rightptr];theArray[rightptr]=temp;}}

0 0
原创粉丝点击