Java实现快速排序

//Author: ScottChiang 
//Date: June 2012
package com.test.sort;

import java.util.Random;


public class QuickSort {

    public static void main(String[] args) {
        //随机产生一个数组
        Random random = new Random();
        int countNumbers = random.nextInt(17) + 3 ;
        int []randomArray = new int[countNumbers];
        for(int i=0; i< countNumbers; i++){
            randomArray[i] = random.nextInt(99)+1;
        }
        
        //打印排序前的数组
        printArray(randomArray);
        // 快速排序
        quickSort(randomArray, 0, randomArray.length - 1);
        // 打印排序后的数组
        printArray(randomArray);
        
        
    /*       
     int []myarray = {49,38, 65, 97, 76, 13, 27};
        //打印排序前的数组
        printArray(myarray);
        // 快速排序
        quickSort(myarray, 0, myarray.length - 1);
        // 打印排序后的数组
        printArray(myarray);
    */
        
    }
    public static void quickSort(int array[], int from, int to){
        
        if(from < to){
            //System.out.println("排序前");
            //printPartArray(array, from, to);
            int pivot = array[to];
            int i = from - 1;
            int j = to + 1;
            while(true){
                while(array[++i] < pivot);
                while(array[--j] > pivot);
                if(i >= j) 
                    break;
                int tempValue = array[i];
                array[i] = array[j];
                array[j] = tempValue;
            }
            //System.out.println("排序后");
            //printPartArray(array, from, to);
            quickSort(array, from, i - 1);//将排序前,小于等于pivot的数,放到左集合再排序
            quickSort(array, j + 1, to);//将排序后,大于pivot的数,放到右集合再排序
        }
    }

    public static void printArray(int []arr){
        for(int temp:arr){
            System.out.print(temp+ " ");
        }
        System.out.println("");
    }
    
    public static void printPartArray(int []arr, int f, int t){
        for(int i = f; i<= t; i++){
            System.out.print(arr[i]+" ");
        }
        System.out.println("");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值