-
Notifications
You must be signed in to change notification settings - Fork 11
/
快排的递归与非递归实现(腾讯面试)
88 lines (82 loc) · 2.15 KB
/
快排的递归与非递归实现(腾讯面试)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.*;
//快排的实现
public class quikSort{
//(1)递归实现快速排序
public static void quickSort(int[]s,int l,int r){
if(l<r)
{
int i=l;
int j=r;
int pivot=s[l]; //取每个子数组的第一个数为基点
while(i<j)
{
while(i<j&&s[j]>pivot) //从右向左
j--;
if(j>i)
{
s[i++]=s[j];
}
while(i<j&&s[i]<pivot) //从左向右
i++;
if(i<j)
{
s[j--]=s[i];
}
}
s[i]=pivot;
quickSort(s,l,i-1);
quickSort(s,i+1,r);
}
}
//非递归实现快速排序
public static void NonRecQuickSort(int[] a,int start,int end) {
LinkedList<Integer> stack = new LinkedList<Integer>(); //用栈模拟
if(start < end) {
stack.push(end);
stack.push(start);
while(!stack.isEmpty()) {
int l = stack.pop();
int r = stack.pop();
int index = partition(a, l, r);
if(l < index - 1) {
stack.push(index-1);
stack.push(l);
}
if(r > index + 1) {
stack.push(r);
stack.push(index+1);
}
}
}
}
public static int partition(int[] a, int start, int end) {
int pivot = a[start];
while(start < end) {
while(start < end && a[end] >= pivot)
end--;
a[start] = a[end];
while(start < end && a[start] <= pivot)
start++;
a[end] = a[start];
}
a[start] = pivot;
return start;
}
//打印数组的值
public static void PrintArray(int[]arr)
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[]args)
{
int[]arr={3,6,5,2,5,4,3,8};
PrintArray(arr);
//quickSort(arr,0,arr.length-1);
NonRecQuickSort(arr,0,arr.length-1);
PrintArray(arr);
}
}