排序之快速排序

来源:互联网 发布:c语言软件 编辑:程序博客网 时间:2024/06/05 14:56


public class QuickSort {public  int[] str;public  int getPartition(int[] str,int low,int high){int tmp = str[low];while(low<high){while(low<high&&str[high]>tmp)high--;str[low]=str[high];while(low<high&&str[low]<tmp)low++;str[high]=str[low];for (int i = 0; i < str.length; i++) {System.out.print(str[i]+" ");}System.out.println();}str[low]=tmp;return low;}int[] quickSort(int low,int high){if(low<high){int i = getPartition(str, low, high);quickSort(low, i-1);quickSort(i+1,high);}return str;}public static void main(String[] args) throws InstantiationException, IllegalAccessException {int[] str = {0,2,1};QuickSort qs = QuickSort.class.newInstance();qs.str=str;qs.quickSort(0, str.length-1);for (int i = 0; i < str.length; i++) {System.out.print(str[i]+" ");}}}
以上是快速排序的实现代码。
代码的实现思想是:
1、将数组的第一位置即a[0]作为基准,把数组变成两部分,第一部分是前面的数小于“基准”,第二部分是后面的数大于“基准”
2、将分好的两部分,分别再做1操作。递归操作一直到low=high。

0 0
原创粉丝点击