快速排序算法

来源:互联网 发布:三网软件 编辑:程序博客网 时间:2024/05/14 14:59
import java.util.Arrays;public class QuickSort {    //交换值    static void swap(int[] a,int i,int j){        int temp=a[i];        a[i]=a[j];        a[j]=temp;    }    //确定基准值    static int part(int[] p,int l,int r){        int i=l;        int j=r+1;        int x=p[l];            while(--j>i){                if(p[j]>x)continue;                while(++i<j){                    if(p[i]<x)continue;                     swap(p,i,j);                     break;                }            }        swap(p,l,i);        return i;    }    //快速排序算法    static void quickSort(int[] a ,int l,int r){        if(l<r){            int q=part(a,l,r);            quickSort(a, l, q-1);            quickSort(a, q+1, r);        }    }    public static void main(String[] args) {        int[] a={4,8,3,7,1,5,6,2,56,89,47,4,8,5,5,5,5,5,4};        quickSort(a, 0, a.length-1);        System.out.println(Arrays.toString(a));    }}output:[1, 2, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 8, 47, 56, 89]
0 0
原创粉丝点击