快速排序

(参考:http://www.cnblogs.com/CBDoctor/p/4077574.html

(性能分析参考:http://www.cnblogs.com/zabery/archive/2011/07/27/2118353.htmlhttp://www.cnblogs.com/CheeseZH/p/5165985.html

import java.util.Scanner;

import com.sun.corba.se.spi.orbutil.fsm.Input;
import com.sun.org.apache.bcel.internal.generic.SWAP;

/**
 * Project Name:Algorithm
 * File Name:FastSort.java
 * Package Name:
 * Date:2017年9月29日上午8:25:42
 * Copyright (c) 2017, 2692613726@qq.com All Rights Reserved.
 *
 */

/**
 * ClassName:FastSort 
 * Function: 快速排序。测试数据:4 5 6 0 1 7 2 3    6 1 2 7 9 3 4 5 10 8
 * Reason:      (1)快速排序的最差时间复杂度和冒泡排序是一样的都是O(N2),它的平均时间复杂度为O(NlogN)
 *            (2) 不稳定的排序算法            
 * Date:     2017年9月29日 上午8:25:42 
 * @author   michael
 * @version  
 * @since    JDK 1.7
 * @see      
 */
public class FastSort {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = "";
        while(scanner.hasNext()){
            input = scanner.nextLine();
            System.out.println("输入值:" + input);
            long startTime = System.currentTimeMillis();
            String[] str = input.split(" ");
            int[] arr = new int[str.length];
            // 字符串数组转化成int数组
            for (int i = 0; i < str.length; i++) {
                arr[i] = Integer.parseInt(str[i]);
            }
            sort(arr, 0, arr.length-1);
        
        }
    }
    
    /*
     * 快速排序算法
     * */
    public static void sort(int[] arr, int left ,int right){
        //结束迭代
        if(left > right){
            return;
        }
        int i = left;
        int j = right;
         
        int temp = arr[left];
        
        while(i!=j){
            while (arr[j]>=temp&& i<j) {
                j--;
            }
            while(arr[i]<=temp&& i<j){
                i++;
            }
            if(i<j){
                swap(arr, i, j);
            }
        }
        //注意,不是交换的0和i,而是left和i,交换都还是发生在原来的数组内
        swap(arr,i,left);
        System.out.println("本轮循环结果为:");
        for (int j2 = 0; j2 < arr.length; j2++) {
            System.out.print(arr[j2]);
        }
        sort(arr, left, i-1);
        sort(arr, j+1, right);
    }
    
    /*
     * 交换函数
     * */
    public static void swap(int[] arr,int a,int b){
        int temp;
        temp  = arr[a];
        arr[a] =arr[b];
        arr[b] =temp;
    }
}

原文地址:https://www.cnblogs.com/Michael2397/p/7613610.html