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
|
package sort.algorithm; import java.util.Stack; //快速排序的非遞歸實現,利用系統的棧stack public class QuickSortNonRecursion
{ public static void main(String[]
args) { QuickSortNonRecursion
qsnr = new QuickSortNonRecursion(); int []
array = { 0 , 2 , 11 , 121 , 18 , 99 , 3 , 5 , 101 , 22 , 9 , 100 }; qsnr.quicksort(array); for ( int i
: array) { System.out.print(i
+ "
" ); } } public void quicksort( int []
array) { if (array
== null ||
array.length == 1 ) return ; //存放開始與結束索引 Stack<Integer>
s = new Stack<Integer>(); //壓棧 s.push( 0 ); s.push(array.length
- 1 ); //利用循環裏實現 while (!s.empty())
{ int right
= s.pop(); int left
= s.pop(); //如果最大索引小於等於左邊索引,說明結束了 if (right
<= left) continue ; int i
= partition(array, left, right); if (left
< i - 1 )
{ s.push(left); s.push(i
- 1 ); } if (i
+ 1 <
right) { s.push(i+ 1 ); s.push(right); } } } //找到軸心,進行交換 public int partition
( int []
data, int first, int end) { int temp; int i=first,j=end; if (first<end) { temp=data[i]; //當i=j的時候,則說明掃描完成了 while (i<j) { //從右邊向左邊掃描找到一個小於temp的元素 while (j>i&&data[j]>temp)j--; if (i<j) { //將該元素賦值給temp data[i]=data[j]; //賦值後就應該將i+1指向下一個序號 i++; } //然後從左邊向右邊開始掃描,找到一個大於temp的元素 while (i<j&&temp>data[i])i++; if (i<j) { //將該元素賦值給temp data[j]=data[i]; //賦值後就應該將j-1指向前一個序號 j--; } } //將軸數據放在i位置中 data[i]=temp; } return i; } } |
java版快速排序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.