Java实现快速排序递归和非递归

时间:2021-11-23 22:16:18
/**
* 快速排序
* */
public class QuickSort{


/**
* 递归一
* */
public static void sort1(int[] arr, int start, int end) {
if(start < end){
//初始先将第一个值
int pvoit = arr[start];
int left = start;
int right = end;
System.out.println("===================================================================");
while(left < right){
System.out.println(" left=" + left + ", right=" + right + ", pvoit=" + pvoit);
while(left < right && arr[right] >= pvoit){
right --;
}
if(left < right){
arr[left ++ ] = arr[right];
}

while(left < right && arr[left] <= pvoit){
left ++ ;
}
if(left < right){
arr[right --] = arr[left];
}
System.out.println(Arrays.toString(arr));
}
System.out.println("===================================================================");
arr[left] = pvoit;
sort1(arr, start, left - 1);
sort1(arr, left + 1, end);
}
}

/**
* 递归二
* */
public static void sort2(int[] arr, int start, int end){
if(start < end){
int povit = RandomUtil.rangeRandom(start, end);
int left = start;
int right = end;
while(left < right){
while(left < right && left != povit && arr[left] <= arr[povit]){
left ++ ;
}
if(left < right){
swap(arr, left, povit);
povit = left;
}
while(left < right && right != povit && arr[right] >= arr[povit]){
right --;
}
if(left < right){
swap(arr, right, povit);
povit = right;
}
}

sort2(arr, start, left - 1);
sort2(arr, left + 1, end);
}
}

/**
* 非递归实现快速排序
* */
public static void sort3(int[] arr, int start, int end){
if(start < end){
Stack<Integer> startStack = new Stack<Integer>();
Stack<Integer> endStack = new Stack<Integer>();

startStack.push(start);
endStack.push(end);

while(startStack.size() > 0 && endStack.size() > 0){
int tempStart = startStack.pop();
int tempEnd = endStack.pop();
if(tempStart < tempEnd){
int povit = RandomUtil.rangeRandom(tempStart, tempEnd);
int left = tempStart;
int right = tempEnd;

while(left < right){
while(left < right && left != povit && arr[left] <= arr[povit]){
left ++ ;
}
if(left < right){
swap(arr, left, povit);
povit = left;
}
while(left < right && right != povit && arr[right] >= arr[povit]){
right --;
}
if(left < right){
swap(arr, right, povit);
povit = right;
}
}
startStack.push(tempStart);
startStack.push(left + 1);
endStack.push(left - 1);
endStack.push(tempEnd);
}
}
}
}

public static void swap(int[] arr, int i, int j){
if(arr != null && i != j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

public static void main(String[] args) {
int[] arr = {2, 1,6,3,4,11,2,3,5,6};
sort3(arr, 0, arr.length-1);

System.out.println(Arrays.toString(arr));
}
}