快速排序

public class QuickSort {

    
    static void quick_sort(int s[], int start_index, int last_index)  
    {  
        if (start_index < last_index)  
        {  
            int i = start_index, j = last_index, x = s[start_index];  
            while (i < j)  
            {  
                while(i < j && s[j] >= x) // 从右向左找第一个小于x的数  
                    j--;    
                if(i < j)   
                    s[i++] = s[j];  
                  
                while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数  
                    i++;    
                if(i < j)   
                    s[j--] = s[i];  
            }  
            s[i] = x;  
            quick_sort(s, start_index, i - 1); // 递归调用   
            quick_sort(s, i + 1, last_index);  
        }  
    }
    
    
     public static void quickSort(int[] arr,int low,int high){
            int i,j,temp,t;
            if(low>high){
                return;
            }
            i=low;
            j=high;
            //temp就是基准位
            temp = arr[low];
            while (i<j) {
                //先看右边,依次往左递减
                while (temp<=arr[j]&&i<j) {
                    j--;
                }
                //再看左边,依次往右递增
                while (temp>=arr[i]&&i<j) {
                    i++;
                }
                //如果满足条件则交换
                if (i<j) {
                    t = arr[j];
                    arr[j] = arr[i];
                    arr[i] = t;
                }

            }
            //最后将基准为与i和j相等位置的数字交换
             arr[low] = arr[i];
             arr[i] = temp;
            //递归调用左半数组
            quickSort(arr, low, j-1);
            //递归调用右半数组
            quickSort(arr, j+1, high);
        }
    
    public static void main(String[] args) {
        int[] a = {46,23,56,23,6,47,534,76};
//        quick_sort(a,0,a.length-1);
        quickSort(a,0,a.length-1);
    }
    
}

 

posted @ 2018-05-04 15:22  秋水秋色  阅读(120)  评论(0编辑  收藏  举报