<pre name="code" class="java">package com.test.linked;
public class QuickSort {
public class Array{
private int[] Myarray;
private int size;
public Array(int max){
Myarray=new int[max];
size=0;
}
/**
* 插入数据
* @param value
*/
public void insert(int value){
Myarray[size]=value;
size++;
}
/**
* 排序
*/
public void sort(){
reQuickSort(0,size-1);
}
/**
* 排序,利用递归将数组分为更小的两个数组
* @param left
* @param right
*/
public void reQuickSort(int left,int right){
if(right-left<=0){
return;
}else{
int center=Myarray[right];
int partition=partitionArray(left,right,center);
reQuickSort(left,partition-1);
reQuickSort(partition+1,right);
}
}
/**
* 定义枢纽(center)位置
* @param left
* @param right
* @param center
* @return
*/
public int partitionArray(int left,int right,int center){
int leftpart=left-1;
int rightpart=right;
while(leftpart<rightpart){
while(Myarray[++leftpart]<center&&leftpart<right);//找到比center更大的数
while(rightpart>=left&&Myarray[--rightpart]>center);//找到比center更小的数
if(leftpart>=rightpart){
break;
}else{
swap(leftpart,rightpart);// 将两数交换
}
}
swap(leftpart,right);//重新记录枢纽的位置
return leftpart;//因为left和right交换所以返回leftpart
}
/**
* 交换数据
* @param leftpart
* @param rightpart
*/
public void swap(int leftpart,int rightpart){
int temp=Myarray[leftpart];
Myarray[leftpart]=Myarray[rightpart];
Myarray[rightpart]=temp;
}
/**
* 显示数组
*/
public void display(){
System.out.println("array begin");
for (int i = 0; i < size; i++) {
System.out.println(Myarray[i]);
}
}
}
public static void main(String[] args){
int max=10;
QuickSort sort=new QuickSort();
Array test=sort.new Array(10);
for (int i = 0; i <max ; i++) {
test.insert((int) (Math.random()*87));
}
test.display();
test.sort();
test.display();
}
}
数据:
<pre name="code" class="java">array begin
21
81
0
48
46
86
76
30
17
2
array begin
0
2
17
21
30
46
48
76
81
86