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(""); } }

 

posted @ 2013-04-08 13:23  ScottChiang  阅读(414)  评论(0)    收藏  举报