JAVA實現排序-快速排序-棧實現快速排序
import java.util.Stack;
//迴圈實現
public class QuickStack {
public static void print(int[] arr){
for(int n=0;n<arr.length;n++){
System.out.print(arr[n]+" ");
}
System.out.println();
}
public static void fun(int[] a, int low, int high){
Stack<Integer> stack = new Stack<Integer>();
if(low < high){
stack.add(low);
stack.add(high);
while(!stack.isEmpty()){
int hi = stack.pop();
int lo = stack.pop();
int key = partition(a, lo, hi);
if(lo < key-1){
stack.push(lo);
stack.push(key-1);
}
if(hi > key){
stack.push(key+1);
stack.push(hi);//這樣,最後入棧的就是key右邊的部分,則下一次迴圈先處理key右邊的部分
}
}
}
}
public static int partition(int[] a, int low, int high){
int key = a[low];
while(low<high){
while(a[high]>=key&&low<high){//大於等於key的陣列元素不需要移動
high--;
}
a[low] = a[high];
while(a[low]<=key&&low<high){//小於於等於key的陣列元素不需要移動
low++;
}
a[high] = a[low];
}
a[low] = key;
print(a);
return low;
}
public static void main(String[] args) {
int[] arr = {49,38,65,97,76,13,27,49,55,4};
fun(arr, 0, arr.length-1);
}
}