Java实现快速排序

来源:互联网 发布:java按键监听器 编辑:程序博客网 时间:2024/06/09 21:40

        最近在看快速排序算法,一开始觉得看懂了。后来写代码遇到一些问题;所以想大致讲一下我在学习快速排序过程的理解;

        首先快速排序是冒泡排序的一种变化,也是对数组中符合某些条件的位置进行互换;然后有递归的思想在里面;好了直接上代码吧;Java实现的;

package MeiTuan;

import java.util.Arrays;

public class QuickSort {

    
    public static void main(String[] args) {
        
        int []a={4,12,34,1,4,2,34,23,11,67,879};
        QuickSort.sort(a, 0, a.length-1);
        System.out.println(Arrays.toString(a));
        
    }
    
    public static void sort(int []a,int low,int high){
        
        int l=low;
        int h=high;
        int pre=a[l];
        
        while(l<h){
            while(l<h && a[h]>=pre)
                h--;
            
            if(l<h){
                int temp=a[h];
                a[h]=a[l];
                a[l]=temp;
                l++;
            }
            
            while(l<h && a[l]<=pre)
                l++;
            
            if(l<h){
                int temp=a[l];
                a[l]=a[h];
                a[h]=temp;
                h--;
            }
            
        }
        if(l>low) sort(a,low,h-1);
        if(h<high) sort(a,l+1,high);
    }

}

0 0