分治法的基本思想是:将原问题分解为若干个规模更小但结构与原问题相似的子问题。递归地解这些子问题,然后将这些子问题的解组合为原问题的解。
package com.thoughtworks;
public class QSort
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO 自动生成方法存根
quicksort qs = new quicksort();
int data[] = {44,22,2,32,54,22,88,77,99,11};
qs.data = data;
qs.sort(0, qs.data.length-1);
qs.display();
}
}
class quicksort
{
public int data[];
private int partition(int sortArray[],int low,int hight)
{
int key = sortArray[low];
while(low<hight)
{
while(low<hight && sortArray[hight]>=key)
hight--;
sortArray[low] = sortArray[hight];
while(low<hight && sortArray[low]<=key)
low++;
sortArray[hight] = sortArray[low];
}
sortArray[low] = key;
return low;
}
public void sort(int low,int hight)
{
if(low<hight)
{
int result = partition(data,low,hight);
sort(low,result-1);
sort(result+1,hight);
}
}
public void display()
{
for(int i=0;i<data.length;i++)
{
System.out.print(data[i]);
System.out.print(" ");
}
}
}
2 11 22 22 32 44 54 77 88 99