input:
13 24 3 56 34 3 78 12 29 49 84 51 9 100
13 24 3 56 34 4 78 12 29 49 84 51 9 99
output:
3 3 9 12 24 29 34 49 51 56 78 84 100
3 4 9 12 24 29 34 49 51 56 78 84 99
用栈来实现递归,单次划分出来的结果和上边界不停地存放到栈中,这样来实现分治。
代码:
import java.util.*;
public class Main
{
//一次划分排序
public static int partition(int[]element,int start,int end){
int key = element[start];
while(start < end){
while(start < end && element[end] >= key){
end --;
}
element[start] = element[end];
while(start < end && element[start] <= key){
start ++;
}
element[end] = element[start];
}
element[start] = key;
return start;
}
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
// int e_num = Integer.parseInt(scan.nextLine());
// while(e_num > 0){
int num = scan.nextInt();//元素数
int[] element = new int[num];
//初始化数组
for(int i=0;i < num;i ++){
element[i] = scan.nextInt();
}
Stack<Integer> stack = new Stack<>();
stack.push(0);
stack.push(num-1);
while (!stack.isEmpty()) {
int r = stack.pop();
int l = stack.pop();
if (l < r) {
int temp = partition(element, l, r);
stack.push(l);
stack.push(temp - 1);
stack.push(temp + 1);
stack.push(r);
}
}
for(int i=0;i < num;i ++){
if(i == num-1){
System.out.print(element[i]);
}else{
System.out.print(element[i]+" ");
}
}
System.out.println();
// e_num --;
}
}
}