package com.cuiqi.test;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
/**
*
*
快速排序法 * Created by tracy on 2017/7/18.
*/
public class QuickSort {
public static void main(String...args){
out.print("请输入10个数字,用空格隔开:");
int[] numbers = inputNumbers();
swap(0,numbers.length - 1,numbers);
for(int i=0; i<numbers.length;i++){
out.print(numbers[i]);
if(i != numbers.length-1){
out.print(",");
}
}
}
/**
* @return
*/
private static int[] inputNumbers(){
Scanner scanner = new Scanner(in);
String numStr = scanner.nextLine();
String[] nums = numStr.trim().split("\\s+");
int[] numbers = new int[nums.length];
for(int i=0;i<nums.length;i++){
try {
int number = Integer.valueOf(nums[i]);
numbers[i] = number;
}catch (NumberFormatException e){
out.print(String.format("您输入的%s不是数字,请重新输入:",nums[i]));
numbers[i] = input();
}
}
return numbers;
}
private static int input(){
Scanner scanner = new Scanner(in);
try {
return scanner.nextInt();
}catch (Exception e){
out.print("您输入的不是数字,请重新输入“");
return input();
}
}
private static void swap(int begin,int end,int[] numbers){
if(begin >= end){
return;
}
int base = numbers[begin];
int blockIndex = begin;
int current = end;
int index = -1;
for(int i = 0; i<end - begin; i++){
Integer currentNum = numbers[current];
if(currentNum.compareTo(base) == index){
numbers[blockIndex] = currentNum;
index = 0 - index;
int oldBlockIndex = blockIndex;
blockIndex = current;
current = oldBlockIndex + index;
numbers[blockIndex] = base;
}else{
current+=index;
}
}
swap(begin, blockIndex - 1, numbers);
swap(blockIndex + 1, end, numbers);
}
}