快速排序-转自java数据结构与算法
2014-03-31 14:29
204 查看
package cn.ccnu.lzc; import java.util.Random; public class QuickSort { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int 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 stub int temp=theArray[leftptr]; theArray[leftptr]=theArray[rightptr]; theArray[rightptr]=temp; } }
相关文章推荐
- java数据结构和算法------快速排序
- java数据结构和算法-3,快速排序
- 几种常见排序算法之Java实现(插入排序、希尔排序、冒泡排序、快速排序、选择排序、归并排序)
- Java数据结构与算法之排序
- 【算法-排序之二】快速排序
- 【一周一算法】算法3:最常用的排序——快速排序
- 常用的选择排序.Shell排序.快速排序.冒泡排序.插入排序的算法
- 白话经典算法系列之六 快速排序 快速搞定
- 快速排序的算法优化要点
- 【排序及算法】冒泡/选择/插入/快速排序、顺序查找/折半查找算法
- 算法导论--------快速排序
- 【重温经典算法之二】快速排序
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 第十六周 项目1 验证算法 快速排序
- 转:快速排序的算法思想
- 【数据结构与算法】快速排序
- (第十六周项目1)验证算法(4)快速排序
- 《算法(第四版)》排序-----快速排序