Вы находитесь на странице: 1из 702

32.973.

2-018
004.422.63
29

.
29 Java. Computers Science. 2- .
.: , 2013. 704 .: . ( computer science).

ISBN 978-5-496-00740-5
-
. , -
,
. , -
. -
Java, -
, C++.
,
- . -
, :
, , , , -
, , , .
.
12+ ( 12 . 29 2010 .
436-.)
32.973.2-018
004.422.63

Sams Publishing. .

.
, , ,
. , ,

, .

ISBN 978-0672324536 . Sams Publishing, 2003


ISBN 978-5-496-00740-5 , 2011
,
, 2011

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
- . . . . . . . . . . . . . . . . . . . . . . . . . . 30
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
- . . . . . . . . . . . . . . . . . . . . . . 33
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6

Java C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Array Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
LowArray LowArrayApp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
highArray.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Ordered Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Java . . . . . . . . . . . . . . . . . . . . . . . . 67
find() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
OrdArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
, . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Person . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
classDataArray.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
O- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
: . . . . . . . . . . . . 80
: N . . . . . . . . . . . . . . . . . . . . . . 80
: log(N) . . . . . . . . . . . . . . . . . . 80
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
BubbleSort Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Java . . . . . . . . . . . . . . . . . . . . 94
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
SelectSort Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Java . . . . . . . . . . . . . . . 101
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
InsertSort Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Java . . . . . . . . . . . . . . . 108
. . . . . . . . . . . . . . . . . . . . . . . . . . . 111
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Java . . . . . . . . . . . . . . . . . . . . . . 112
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Stack Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
1. . . . . . . . . . 129
2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Queue Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
8

Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
The PriorityQ Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Java . . . . . . . . . . . . . . . . . . . . 150
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
. . . . . . . . . . . . . . . . . . . 154
. . . . . . . . . . . . . . . . . 154
. . . . . . . . . . . . . . . . . . . . 170
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
LinkList Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
LinkList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
linkList.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
find() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
delete() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
. . . . . . . . . . . . . . . . . . . . . . . . 201
. . . . . . . . . . . . . . . . . . . . . . 204
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
. . . . . . . . . . . . 209
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Java . . . 211
sortedList.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
9


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
doublyLinked.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
. . . . . . . . . . . . . . . . . . . . 226
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
interIterator.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
atEnd() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
n- . . . . . . . . . . . . . . . . . . . . . . . . 244
n- . . . . . . . . . 245
triangle.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
. . . . . . . . . . . . . . . . . . . . . . . . . . 262
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Towers Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
towers.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
. . . . . . . . . . . . . . . . . . . . . . . . . . . 268
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
MergeSort Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
mergeSort.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
10

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297

7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
: . . . . . . . . . . . 300
N- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Shellsort Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Java . . . . . . . . . . . . . . . . . . . . . . . . 305
. . . . . . . . . . . . . . . . . . . . . . . . . . 307
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Partition Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
QuickSort1 Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
O(N2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
. . . . . . . . . . . . . . . . . . . . . . . . . . . 340
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
. . . . . . . . . . . . . . . . . . . . . . . 346
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Binary Tree Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
11


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
1. . . . . . . . . . . . . . . . . . . . . . . . . 368
2. . . . . . . . . . . . . . . . . . . . . . 370
3. . . . . . . . . . . . . . . . . . . . . . . 372
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
tree.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401

9. - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
. . . . . . . . . . . . . . . . . . . . . . 404
O(N) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
RBTree Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Del . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Flip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
RoL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
RoR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
R/B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Find? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
1. . . . . . . . . . . . . . . . . . . . . . . . . . 411
2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
12

4. . . . . . . . . . . . . . . . . . . . . . . . . 413
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
- . . . . . . . . . . . . . . . . 414
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
. . . . . . . . . . . . . . . . . . . . . . . . 420
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435

10. 2-3-4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436


2-3-4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
2-3-4 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
2-3-4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
2-3-4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Tree234 Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
2-3-4 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
DataItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Tree234 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Tree234App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
tree234.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
2-3-4 - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
2-3-4 - . . . . . . . . . . . . 457
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
2-3-4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
13


2-3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
B- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485

11. - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
- Java . . . . 500
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
HashChain Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
. . . . . . . . . . . . . . . . . . 534
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
14

12. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
, ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Heap Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
heap.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
heapSort.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
. . . . . . . . . . . . . . . . . . . . . . . . . 569
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572

13. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
GraphN Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600

Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
. . . . . . . . . . . . . . . . . . . 604
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
15


GraphD Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620

14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
. . . . . . . . . . . . . . . . . . . . 622
: . . . . . . . . . . . . . . . . . . . . . . . . . 622
GraphW Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
mstw.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
GraphDW Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
path.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
. . . . . . . . . . . . . . . . . . . . 656
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664

15. . . . . . . . . . . . . . . . . . . . . . . . . . 666
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
. . . . . . . . . . . . . . . . . 671
16

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
B- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677

. Workshop . . . . . . . . . . . 678
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
Sun Microsystems SDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
- . . . . . . . . . . . . . . . . . . . . 684
- . . . . . . . . . . . . . . . . 684

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
,

,
.

:
.
.
.
.
.
.
.


,
, -
. ,
,
.


,
. -
:
.
.
.
.
.
.
.
.
2-3.
19

.
K N.
.
.


. .
,
.















.
-
- Workshop
,
,
.


: (
) .
-, , -
.
.


-
.
( ).
.

, .
. ; -
for,
.
, for, -
, .
20


. , -
- ,
. ,
Java C++, .
, -
.
,
.


. -
? :
, , -
.
Workshop -
, , -
.

Java
, ,
C
,
C
++
Pas-
cal
(, -
).
.

,
. , ,
. -
. -
.
, -
,
. ,

, -
. ( -
1, ).
, -
- , -
1.
.
21

Workshop

Sams
-
Workshop .
Java
, . ( -
.)
Workshop
-
, ,
. , -
.
, ,
,
. , .
. , -
-, ,
. 20
Workshop .

Workshop
, -
,
. , .
Workshop,
.
Workshop .
, .

Workshop
, -
, .

Java
Java ( ), C
++. , Java

. -
, - ,
.
,
.
Java - ,
- .
, - ()
-
. ,
, ,
Java. 1.
22



, .
,
, .
-
.


- -
.
Java, Java,
.
Java
, -
, -
Java .
, Java, .
C++, Java C++.
(
); 1.


Workshop , Microsoft
Internet

Explorer
Netscape


Communicator
. -
.
Java, Sun Microsystems
(. ).
Micro-

soft Windows .

, Java

. -
; ,
Sun Microsystems (. ).


, -
. ,

.
23


.
1, , .
, , . ,
- ,
, .
, C++, Java,
.
2, , . , -
:
. ,
, . -
Workshop
.
3, , ( )
: , -
. -
Workshop.
4, , , -
(ADT): ,
.
. -
Workshop.
.
5, , ,
.
Java
.
Workshop
, -
, .
6, ,
, . -
,
.
Workshop.
7, ,
: .
Workshop
-
, ( )
.
8, , .
:
. Workshop ,
.
9, - , -
- .
Workshop ,
.
24

10, 2-3-4, 2-3-4


. Workshop , 2-3-4.
2-3 2-3-4 B-,
( ).
11, -, . -
Workshop

: -
, . -
.
12, ,
, .
13, , 14, , . -
,
, -
.
15, ,
.
.
,
Workshop
, -
.
, , SDK Sun Microsystems
,
Workshop .
, ,
.
, , , -
.

!
,
. . ,
, , , ,
.


, ,
comp@piter.com ( , ).
- -
(www.piter.com) Sams www.samspublishing.com.
!
- http://www.piter.com -
.
1

:
?
?
for?
, ?
. -
, ,
, .
, -
, . , -
C++, Java,
.


?
. -
( ). -
, , ,
, - ..
,
.
?
, ,
:
.
.
.
, -
. .
26 1.


, ,
. -
, , .
, ;
,
.
. -
. ,
, .
, , -
.
, . -
, - , -
. ,
. ,
:
?
? ? ?

?
?
, .
?
, -
.
, .

.
.
, .


.
, -
. ,
, .
-
. , ,
.
.
? 27

-
. . -
,
.
13, , 14, . ,
, . ,
, ,
, .



. ( ) -
, . ,
,
, , - .
1.1 ,
.

1.1.

, ,
( ) , -

, ,

LIFO

(-
, )
FIFO (
, )
, -

, , -
(
)
- , , -
. -

2-3-4 , , -
. -
.



28 1.

1.1 ()

- ( - , -
) ( -
), -

, , -


. 1.1, , -
(ADT). , ,
5, .

, ,
. ,
:
.
.
.
,
, -
(, ).
.
; 3,
, 7, .
, -
. 6, . (

Java
; , -
.)

, -
.
29


,
. ,
. , , ,
. -
.

, .
.
. -
, .
,
, ..

.
. ,
.
-
. , .1.1, -
.
Java

( - ) -
.
. Java
( ,
C
++ -
).
:
:
:
:
:
:
:
:
:
:
:
:

. 1.1.
30 1.

. -
. ,

. ,
, . ,
.
, ,
. .1.1 .

, --
. , -
, .
, ,
.

, ,
.


- , (C, Pascal,
BASIC), ,
. , ?
: -
.



. , ,
. ,
( ),
( ).
, -
, furnace_on() furnace_off()
currentTemp ( )
desiredTemp ( ).
- 31

; ,
thermostat.
.
, , -
, ,
.
.


, -
. .
,
. , ,
. , ,
,
. (
) , ,
.
,
.
, ,
. -
.
, , -
, .

: -
, . ,
furnace_on() furnace_off(), currentTemp desiredTemp. Java
.
.
,
. furnace_on() fur-
nace_off() currentTemp desiredTemp.
, ,
.
32 1.

, . -
,
. ,
,
.
.
.
()
. , Java
:
class thermostat
{
private float currentTemp();
private float desiredTemp();

public void furnace_on()


{
//
}

public void furnace_off()


{
//
}
} // thermostat
Java class ;
, (thermostat ).
,
. ;
.
C , ,
C++ C++,
; ( C++?).


( ,

C
). -
Java, new.
-
( ).
? , ,
. ( ,
.)
- 33

thermostat,
thermostat :
thermostat therm1, therm2; //
therm1 = new thermostat(); //
therm2 = new thermostat(); //
,
.


, -
.
?
, ,
(). , therm2
,
therm2.furnace_on();
(. ) (
).
( ) -
. :
().

.
new .
.
,
. ; ,
- . ,
, .

-
- ,
. BankAccount . -
, , ,
. bank.java 1.1.

1.1. bank.java
// bank.java
//
// : C>java BankApp

34 1.

1.1 ()
////////////////////////////////////////////////////////////////
class BankAccount
{
private double balance; //

public BankAccount(double openingBalance) //


{
balance = openingBalance;
}

public void deposit(double amount) //


{
balance = balance + amount;
}

public void withdraw(double amount) //


{
balance = balance - amount;
}

public void display() //


{
System.out.println("balance=" + balance);
}

// BankAccount
////////////////////////////////////////////////////////////////
class BankApp
{
public static void main(String[] args)

{
BankAccount ba1 = new BankAccount(100.00); //

System.out.print("Before transactions, ");


ba1.display(); //

ba1.deposit(74.35); //
ba1.withdraw(20.00); //

System.out.print("After transactions, ");


ba1.display(); //
} // main()
} // BankApp

:
Before transactions, balance=100
After transactions, balance=154.35
- 35

bank.java . BankAccount -
( ).
BankApp .

BankApp
1.1 MS-DOS,
java BankApp C:
C:\>java BankApp
java BankApp
main(). Java main();
main(), 1.1 (
String[] args main() ).
main() BankAccount
100.00; :
BankAccount ba1 = new BankAccount(100.00); //
System.out.print() , (Before
transactions:), :
ba1.display();
:
ba1.deposit(74.35);
ba1.withdraw(20.00);
.

BankAccount
BankAccount ;
balance. . deposit()
, withdrawal() , dis-
play() .

BankAccount ,
.
, BankAccount().
, .
.

deposit() .

Public private
public private BankAccount.
, ,
36 1.

. balance private, -
. , -
. , main()
balance, main() BankAccount.
BankAccount public ( ),
.
main() deposit(), withdrawal() display().
, .

. , -
, .


--
: .
(
) , .
,
. secretary ()
employee ()
typingSpeed ( ),
employee.
Java .
, .

-
. , -

.

. ,
. -
,
.
, display() secretary
display secretary, manager
display, manager. -
.
, , -
. -
,
. ,
, -
.
Java C++ 37

,
, . ,

, .
(software engineering)
.

-
. ,
, , , ,
, .
,
. -
, ,
. ,
, ,
.

. ?
? Java?
, .
,
.

Java C++
C++, Java, .
Java C++.

Java
. -
. -
Java, - C++
.

Java
C++ Java , Java .
C++
. ?
-
. ,
C++.
38 1.

, Java .
, . -
, Java , . ,
, .

Java ( int, float double) -


, . :
int intVar; // int intVar
BankAccount bc1; // BankAccount
, intVar, -
, 127 ( ). ,
bc1 BankAccount.
BankAccount, - . bc1 -
, .
, bc1 ,
.
null. -
intVar ,
. ,
, .
C++
BankAccount bc1;
; -
, . Java
, -
. -
. ( C++ ,
&.)

(=)
Java
, -
C++. C++
bc2 = bc1;
bc1 bc2.
. , Java
, bc1, bc2. -
, bc1 bc2, ,
.
, ,
. -

bc1.withdraw(21.00);
Java C++ 39

bc2.withdraw(21.00);
$21 .
, .
,
, . -
.

new
Java new. Java
new , , C++ ( new
). :
BankAccount ba1;
ba1 = new BankAccount();
.
ba1 ,
. , ,
- .
, new,
? C++ delete. Java

-
.
Java
-
, new, ,
. , .
.
C++
, , -
,
.
Java
( -
).

C++ ;
.

Java
, -
:
void method1()
{
BankAccount ba1 = new BankAccount(350.00);
method2(ba1);
}

void method2(BankAccount acct)


{
}
40 1.

ba1 acct . C++ acct


, ba1.
, ,
, -
.


Java (==) ,
:
int intVar1 = 27;
int intVar2 = intVar1;
if(intVar1 == intVar2)
System.out.println("They're equal");
Java

C

C

+++,
Java
-
, .
, -
:
carPart cp1 = new carPart("fender");
carPart cp2 = cp1;
if(cp1 == cp2)
System.out.println("They're Identical");
C

++ , -
. Java equals() Object:
carPart cp1 = new carPart("fender");
carPart cp2 = cp1;
if( cp1.equals(cp2) )
System.out.println("They're equal");
, Java
Object.


: Java

.
C
++ -
+, *, = ,
, . Java .
, add() +.


, Java . 1.2.
C C++,
true/false, Java boolean.
char , -
.
Java C++ 41

1.2.

boolean 1 true false
byte 8 128 127
char 16 '\u0000' '\uFFFF'
short 16 32,768 +32,767
int 32 2147483 648 +2147483 647
long 64 9223372036854775 808 +9223372036854775807
float 32 1038 10+38; 7
double 64 10308 10+308; 15

C C++ int -
; Java int 32 .
float F (, 3.14159F);
double . long L (-
, 45L); .
Java C C++;
, , -
Java.
, . 1.2 (, String), .

/

Java
/ -
. ,
, , /
, cout /cin C++ printf() /
scanf() C.
Java SDK (Software Development Kit) ,
/

import java.io.*;
.

( ),
String :
System.out.print(var); // var
System.out.println(var); // var
print() , println()
.
42 1.

SDK System.out.print()
System.out.println() System.out.
flush(), .
.
,
+. , ans
33:
System.out.println("The answer is " + ans);
:
The answer is 33


. , -
String. (,
), String .
, ,
,
import java.io.*;
, IOException
InputStreamReader.
.
, :
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
String, ,
Enter. InputStreamReader
BufferedReader .
java.io.*,
throws IOException, . ,
throws IOException ,
, main().


, (
- Enter). ( )
. ,
String
charAt():
Java C++ 43

public static char getChar() throws IOException


{
String s = getString();
return s.charAt(0);
}
charAt() String , -
String; ( 0).
,
.


, String, , -
, . getInt() -
int :
public int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
parseInt() Integer int.
parseLong() long.
SDK , parseInt(),

import java.lang.Integer;
.
. -
, . -
.
,
.


float double , int, -
. double:
public int getDouble() throws IOException
{
String s = getString();
Double aDub = Double.valueOf(s);
return aDub.doubleValue();
}
String Double (D !)
- double. doubleValue()
Double double. float -
Float valueOf() floatValue().
44 1.

Java
java.util , Vector (
), Stack, Dictionary Hashtable.
; , .
, -
.

import java.util.*;
, Java

, -
, . ,
, ,
. ,
, .

-
.
-
.
, .
.
Java .
, , -
.
:
.
,
, .
, -
.
,
.
. ,
.
, -
, LastName.
,
. .
45

.
.
1. ________ -
, ________ ________ .
2. -
_________.
3. :
a) ;
b) ;
c) ;
d) .
4. , , ___________ .
5. - :
a) ;
b) ;
c) ;
d) .
6. :
a) ;
b) ;
c) ;
d) .
7. Java :
a) ;
b) new;
c) ;
d) .
8. , ________ .
9. Java
_____.
10. Java boolean byte _____________ .
( 1 , .)
2

-
.
-
- .
Java, ,
.

, ( ) .

.
Java Workshop,
, . -
Java.
. ,
, Workshop .

O
- -
.

Array Workshop
,
, .
, . -
. ,
:
, .
(
).
, .
, ,
, .
-
Workshop.
Array Workshop 47

, ,
. Ar-
ray Workshop , ,
.
Array Workshop (. ,
Workshop )
C:\>appletviewer Array.html
.2.1 20 , 10 .
. ,
.
, .
, .

. 2.1. Array Workshop

, -
:
Ins .
Find .
Del .
New , Fill
. Fill
0 999 . -
, 60 , , -

.
, ,
; . -
, No Dups .
48 2.

: 20 10 ,
(No Dups). ,
. , Ins. -
:
Enter key of item to insert
( 678) , -
. (, .)
Ins; :
Will insert item with key 678

.
:
Inserted item with key 678 at index 10
Workshop
. ,
. Array
. -
, ,
.
.
,
,
. , -
. , -
.

, Find.
() . , -
, Find.
. ,
0,
. -
:
Checking next cell, index = 2
,
Have found item with key 505
( , ). , -
.
Array Workshop 49

, -
, , .
:
(, ). -
, , , -
. N ,
, , N/2.

N .
,
, (N/2 )
( ).

, . -
,
. -
, . ( , ,
,
, .)
, -
, , (
). , -
,
. , -
.
, .
, -

, . . 2.2.

. 2.2.
50 2.

, 5 ( 38 . 2.2) 6
5, 7 6 -
.
Del.
( ) N/2
( N/2)
. N .


, -
. ,
, ,
.
, , -
, .
, ,

Array

Workshop
. -
New ,
. Dups OK No Dups.
, ,

,
. ,
, ,
1 N. .


, . -

. ,
. ,
:
.
Dups OK -
. -
N ,
.


, :
. : , -
, , -
.
Array Workshop 51


,
. -
N/2
N/2 .
.

, , , . -
N () N/2 .
.
:
. , -
. ,
, .
, , Dups OK,
- .
2.1
, . N
. .

2.1.

N/2 N
, ,
N/2 , N/2 N , N/2

Array
Workshop.
N N/2 ,
. ,
:
, N , log(N) N2 .


Array

Workshop

, , -
. ,
.
( ) . -

, .
52 2.

Java

.
,
Java.
Java , C
C++ . Java C C++
( ), Java
.


1, , Java

-
: (int, double ..) . -
( -, C++)
, Java .
new:
int[] intArray; //
intArray = new int[100]; //
// intArray
:
int[] intArray = new int[100];
[] , ,
.
, :
int intArray[] = new int[100]; //
[] int , [] ,
.
, (intArray
) . - , intArray
.
length,
( ) :
int arrayLength = intArray.length; //
,
.



. -
:
Java 53

temp = intArray[3]; //
intArray[7] = 66; // 66
, Java, C C++, 0,
10 0 9.
0 1, -
.

, -
0 . C++ ,
(). ,
:
autoData[] carArray = new autoData[4000];
,
null. , -
null, null. :
, , .
, 0,
:
int[] intArray = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 };
new
( ).
.
.


. -
, -
- . 2.1
array.java.

2.1. array.java
// array.java
// Java
// : C>java arrayApp
////////////////////////////////////////////////////////////////
class ArrayApp
{
public static void main(String[] args)
{
long[] arr; //

54 2.

2.1 ()
arr = new long[100]; //
int nElems = 0; //
int j; //
long searchKey; //
//--------------------------------------------------------------
arr[0] = 77; // 10
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // 10
//--------------------------------------------------------------
for(j=0; j<nElems; j++) //
System.out.print(arr[j] + " ");
System.out.println("");
//--------------------------------------------------------------
searchKey = 66; // 66
for(j=0; j<nElems; j++) //
if(arr[j] == searchKey) // ?
break; // -
if(j == nElems) // ?
System.out.println("Can't find " + searchKey); //
else
System.out.println("Found " + searchKey); //
//--------------------------------------------------------------
searchKey = 55; // 55
for(j=0; j<nElems; j++) //
if(arr[j] == searchKey)
break;
for(int k=j; k<nElems-1; k++) //
arr[k] = arr[k+1];
nElems--; //
//--------------------------------------------------------------
for(j=0; j<nElems; j++) //
System.out.print( arr[j] + " ");
System.out.println("");
}
} // ArrayApp
arr, 10
( ), 66, , -
55 9 .
:
Java 55

77 99 44 55 22 88 11 0 66 33
Found 66
77 99 44 22 88 11 0 66 33
long. ,
, ; int .
. , -
, , -
.
.

-
:
arr[0] = 77;
, , nElems.

searchKey . ,
, searchKey.
j ,
, , . -
(Found 66 Cant find 27).

. (-
) , . ,
,
, , nElems
1. -
, .

: -
arr[j].


array.java .
ArrayApp, main(). ,
array.java . -
, -
( ).
56 2.

- .
() -
. .

.


array.java 2.1 -
. -
. ? ,
. -
, (
).
array.java ,
.
LowArray. ,
(LowArrayApp )
. LowArray
LowArrayApp. LowArray ,
. lowArray.java
2.2.

2.2. lowArray.java
// lowArray.java
//
// : C>java LowArrayApp
////////////////////////////////////////////////////////////////
class LowArray
{
private long[] a; // a
//--------------------------------------------------------------
public LowArray(int size) //
{ a = new long[size]; } //
//--------------------------------------------------------------
public void setElem(int index, long value) //
{ a[index] = value; }
//--------------------------------------------------------------
public long getElem(int index) //
{ return a[index]; }
//--------------------------------------------------------------
} // LowArray
////////////////////////////////////////////////////////////////
class LowArrayApp
{
public static void main(String[] args)
{
57

LowArray arr; //
arr = new LowArray(100); // LowArray
int nElems = 0; //
int j; //

arr.setElem(0, 77); // 10
arr.setElem(1, 99);
arr.setElem(2, 44);
arr.setElem(3, 55);
arr.setElem(4, 22);
arr.setElem(5, 88);
arr.setElem(6, 11);
arr.setElem(7, 00);
arr.setElem(8, 66);
arr.setElem(9, 33);
nElems = 10; // 10

for(j=0; j<nElems; j++) //


System.out.print(arr.getElem(j) + " ");
System.out.println("");

int searchKey = 26; //


for(j=0; j<nElems; j++) //
if(arr.getElem(j) == searchKey) // ?
break;
if(j == nElems) //
System.out.println("Can't find " + searchKey);
else //
System.out.println("Found " + searchKey);

// 55
for(j=0; j<nElems; j++) //
if(arr.getElem(j) == 55)
break;
for(int k=j; k<nElems; k++) //
arr.setElem(k, arr.getElem(k+1) );
nElems--; //

for(j=0; j<nElems; j++) //


System.out.print( arr.getElem(j) + " ");
System.out.println("");
}
} // LowArrayApp
////////////////////////////////////////////////////////////////
lowArray.java array.
java, , 55
(26):
77 99 44 55 22 88 11 0 66 33
Can't find 26
77 99 44 22 88 11 0 66 33
58 2.

LowArray LowArrayApp
lowArray.java LowArray
Java. ;
private,
LowArray. LowArray : setElem() ge-
tElem() ,
.
, LowArrayApp, LowArray
. , LowArray , LowArrayApp
. -
; --
.
, ( LowArray -
lowArray.java), (
). , ,
; -
.


, .
?
- .

. 2.3. LowArray

, .
, ,
59

( ) . ,
- LowArray
. ,
.
,
, .
.
,
. ,
.
- ,
. .2.3 -
LowArray.


LowArray lowArray.java .
setElem() getElem()
, , []
Java. , main() LowAr-
rayApp, ,
array.java.
, setElem() getElem()
[]. -
.

. LowArrayApp
getElem() for. ,
LowArrayApp ,
LowArrayApp?
, lowArray.java -
, . ,
, -
.

?
lowArray.java main() LowArrayApp (
) . ,

, . ,
, .
.
60 2.

highArray.java
(
HighArray) . (HighArrayApp)
. setElem() getElem() ;
insert(), find() delete().
, . -
(HighArrayApp) ,
( , ), , -
.
.2.4 HighArray, 2.3
highArray.java.

. 2.4. LowArray

2.3. highArray.java
// highArray.java
//
// : C>java HighArrayApp
////////////////////////////////////////////////////////////////
class HighArray
{
private long[] a; // a
private int nElems; //
//-----------------------------------------------------------
public HighArray(int max) //
{
a = new long[max]; //
nElems = 0; //
}
//-----------------------------------------------------------
61

public boolean find(long searchKey)


{ //
int j;
for(j=0; j<nElems; j++) //
if(a[j] == searchKey) // ?
break; // -
if(j == nElems) // ?
return false; //
else
return true; //
}
//-----------------------------------------------------------
public void insert(long value) //
{
a[nElems] = value; //
nElems++; //
}
//-----------------------------------------------------------
public boolean delete(long value)
{
int j;
for(j=0; j<nElems; j++) //
if( value == a[j] )
break;
if(j==nElems) //
return false;
else //
{
for(int k=j; k<nElems; k++) //
a[k] = a[k+1];
nElems--; //
return true;
}
}
//-----------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(a[j] + " "); //
System.out.println("");
}
//-----------------------------------------------------------
} // HighArray
////////////////////////////////////////////////////////////////
class HighArrayApp
{
public static void main(String[] args)
{
int maxSize = 100; //

62 2.

2.3 ()
HighArray arr; //
arr = new HighArray(maxSize); //

arr.insert(77); // 10
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

arr.display(); //

int searchKey = 35; //


if( arr.find(searchKey) )
System.out.println("Found " + searchKey);
else
System.out.println("Can't find " + searchKey);

arr.delete(00); //
arr.delete(55);
arr.delete(99);

arr.display(); //
}
} // HighArrayApp
////////////////////////////////////////////////////////////////
HighArray . main()
,
lowArray.java: 10 , ( )
. ,
(0, 55 99)
. :
77 99 44 55 22 88 11 0 66 33
Cant find 35
77 44 22 88 11 66 33
, main(). -
, main()
lowArray.java, HighArray.
find() HighArray
, . true false -
, .
insert()
. , ,
Ordered Workshop 63

nElems. main()
.
delete() , -
. ,
; , -
.
nElems.
display() ,
.


lowArray.java (. 2.2) main()
; highArray.java .
(HighArrayApp)
. , ,
HighArray .
. -
.

(
, )
. -
. -
,
.

Ordered Workshop
, -
0,
, .
.

: -
. , -
.
?
.
Ordered Workshop (. 1).
(. 2.5); Array Workshop,
.
64 2.

.
, , .

. 2.5. Ordered Workshop


Ordered Workshop :
. .
, Array:
.
, -
.
. ,
Linear, Find
, , ,
. , . 2.5 400. ,
, 400;
427. , .
Ins Del. Ins -
, - -
. ,
, .
Del.
, Array
, ,
.
, (
).
Ordered Workshop 65



. ,
.


, .
1 100, .
, : ,
.
,
50. , , -
51 100, 75 ( -
51 100).
1 49, 25.
.
, .
.
, 1, 2, 3 .., -
50 .
,
. 2.2 , -
33.

2.2.

0 1100

1 50 149
2 25 2649
3 37 2636
4 31 3236
5 34 3233
6 32 3333
7 33

,
, , , -
1. , , 50 34.
66 2.

Ordered Workshop
Ordered Workshop,
( New).
( 60) : -
. ( Binary).
, Fill.
( ).
, -
, .
,
-
. .2.6 ,
.

. 2.6.

Find , -
. . 2.7
.
60 -
.
. -
?
.
: -
. , -
.
.
Java 67

. 2.7. 2


Java

Java
. -
OrdArray.
find(),
. ,
.

find()
find() -
. :
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;

while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn; //
68 2.

else if(lowerBound > upperBound)


return nElems; //
else //
{
if(a[curIn] < searchKey)
lowerBound = curIn + 1; //
else
upperBound = curIn - 1; //
}
}
}
lowerBound upperBound -
.
, searchKey.
while curIn .
, curIn ,
. , curIn.
. -
, .
: lowerBound upperBound, ,
. ( , , -
.) ;
, nElems,
. , -
nElems-1.
, .
curIn , -
, .
a[curIn] , ,
searchKey.

. 2.8.
Java 69

searchKey , , -
. lowerBound
curIn, , curIn -
.
searchKey a[curIn],
. upperBound , -
curIn. .2.8 ,
.

OrdArray
orderedArray.java highArray.java ( 2.3). -
, find() .

. insert()
. , ,
,
, -
.
, -
insert() ( Ordered
Workshop). , delete() find() -
.
OrdArray size(), -
.
main() find(). If find() nElems,
main() size(), , . -
2.4 orderedArray.java.

2.4. orderedArray.java
// orderedArray.java
//
// : C>java OrderedApp
////////////////////////////////////////////////////////////////
class OrdArray
{
private long[] a; // a
private int nElems; //
//-----------------------------------------------------------
public OrdArray(int max) //
{
a = new long[max]; //
nElems = 0;
}
//-----------------------------------------------------------

70 2.

2.4 ()
public int size()
{ return nElems; }
//-----------------------------------------------------------
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;

while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn; //
else if(lowerBound > upperBound)
return nElems; //
else //
{
if(a[curIn] < searchKey)
lowerBound = curIn + 1; //
else
upperBound = curIn - 1; //
}
}
}
//-----------------------------------------------------------
public void insert(long value) //
{
int j;
for(j=0; j<nElems; j++) //
if(a[j] > value) // ( )
break;
for(int k=nElems; k>j; k--) //
a[k] = a[k-1];
a[j] = value; //
nElems++; //
}
//-----------------------------------------------------------
public boolean delete(long value)
{
int j = find(value);
if(j==nElems) //
return false;
else //
{
for(int k=j; k<nElems; k++) //
a[k] = a[k+1];
nElems--; //
Java 71

return true;
}
}
//-----------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(a[j] + " "); //
System.out.println("");
}
//-----------------------------------------------------------
}
////////////////////////////////////////////////////////////////
class OrderedApp
{
public static void main(String[] args)
{
int maxSize = 100; //
OrdArray arr; //
arr = new OrdArray(maxSize); //

arr.insert(77); // 10
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

int searchKey = 55; //


if( arr.find(searchKey) != arr.size() )
System.out.println("Found " + searchKey);
else
System.out.println("Can't find " + searchKey);

arr.display(); //

arr.delete(00); //
arr.delete(55);
arr.delete(99);

arr.display(); //
}
} OrderedApp
////////////////////////////////////////////////////////////////
72 2.


?
. -
, ,

. , -
, -
, .
, , -
, . ,
.


, ..
, -

.

, -
. ,
, , . ,
,
. 2.3.
,
. 1 100

; 100
. ? 2.3 -
,
.
-
. .
10 5 (N/2) 4 -
. ,
. 100 50 ,
7. 1000
500/10, 1000000 500000/20.
, , ,
.
73

2.3.

10 4
100 7
1000 10
10000 14
100000 17
1000000 20
10000000 24
100000000 27
1000000000 30

. 2.3 : (
) ,
.
.
-
. ?
, , ,
.
( !).
. 2.3 : ,
, ?
,
. . 2.4
.
100 , 6
(64), 7 (128).
, 7 100 . 2.3 , 10
1000 .
,
( . 2.4).
s ( 2, , -
2), r , :
r = 2s
s ( ),
. , s=6, 26, 64.
74 2.

2.4.
s ( , log2(r)) r , 2 (2s)
0 1 20
1 2 21
2 4 22
3 8 23
4 16 24
5 32 25
6 64 26
7 128 27
8 256 28
9 512 20
10 1024 210

,
:
, ,
. , r s.
, , .
:
s = log2(r).
, ()
2. ? r -
2 , 2 r.
2.4 s log2(r).
? -
log

. -
10,
2 3,322. , log10(100) = 2; ,
log2(100) = 2 3,322, 6,644. 7 -
100 . 2.4.
, -
. .
. 2.3, , -
. 10-
( ) 3 4 (
3,322 ).
.
O-.
75



Java
, , -
long. -
,
. ()
. , , , ,
..
, , , ,
..

.

Person
Java .
Person , :
class Person
{
private String lastName;
private String firstName;
private int age;
//-----------------------------------------------------------
public Person(String last, String first, int a)
{ //
lastName = last;
firstName = first;
age = a;
}
//-----------------------------------------------------------
public void displayPerson()
{
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
//-----------------------------------------------------------
public String getLast() //
{ return lastName; }
} // Person
: , . -
, .
Person .
displayPerson() Person, getLast()
lastName , .
76 2.

classDataArray.java
, Person, highArray.java (-
2.3), long.
Person, ;
:
a Person.
(lastName) String, -
equals() ==. getLast()
Person lastName Person, equals() -
:
if( a[j].getLast().equals(searchName) ) // ?
insert() Person (
long).
main() - .
- 10 , , ,
. classDataArray.
java 2.5.

2.5. classDataArray.java
// classDataArray.java
//
// : C>java ClassDataApp
////////////////////////////////////////////////////////////////
class Person
{
private String lastName;
private String firstName;
private int age;
//--------------------------------------------------------------
public Person(String last, String first, int a)
{ //
lastName = last;
firstName = first;
age = a;
}
//--------------------------------------------------------------
public void displayPerson()
{
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
//--------------------------------------------------------------
public String getLast() //
{ return lastName; }
} // Person
77

////////////////////////////////////////////////////////////////
class ClassDataArray
{
private Person[] a; //
private int nElems; //

public ClassDataArray(int max) //


{
a = new Person[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public Person find(String searchName)
{ //
int j;
for(j=0; j<nElems; j++) //
if( a[j].getLast().equals(searchName) ) // ?
break; //
if(j == nElems) // ?
return null; // ,
else
return a[j]; // ,
} // end find()
//-------------------------------------------------------------
//
public void insert(String last, String first, int age)
{
a[nElems] = new Person(last, first, age);
nElems++; //
}
//--------------------------------------------------------------
public boolean delete(String searchName)
{ //
int j;
for(j=0; j<nElems; j++) //
if( a[j].getLast().equals(searchName) )
break;
if(j==nElems) //
return false;
else //
{
for(int k=j; k<nElems; k++) //
a[k] = a[k+1];
nElems--; //
return true;
}
}

78 2.

2.5 ()
//--------------------------------------------------------------
public void displayA() //
{
for(int j=0; j<nElems; j++) //
a[j].displayPerson(); //
}
//--------------------------------------------------------------
} // ClassDataArray
////////////////////////////////////////////////////////////////
class ClassDataApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ClassDataArray arr; //
arr = new ClassDataArray(maxSize); //
// 10
arr.insert("Evans", "Patty", 24);
arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimson", "Henry", 29);
arr.insert("Velasquez", "Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);

arr.displayA(); //

String searchKey = "Stimson"; //


Person found;
found=arr.find(searchKey);
if (found != null)
{
System.out.print("Found ");
found.displayPerson();
}
else
System.out.println("Can't find " + searchKey);

System.out.println("Deleting Smith, Yee, and Creswell");


arr.delete("Smith"); //
arr.delete("Yee");
arr.delete("Creswell");

arr.displayA(); //
}
} // ClassDataApp
////////////////////////////////////////////////////////////////
O- 79

:
Last name: Evans, First name: Patty, Age: 24
Last name: Smith, First name: Lorraine, Age: 37
Last name: Yee, First name: Tom, Age: 43
Last name: Adams, First name: Henry, Age: 63
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Stimson, First name: Henry, Age: 29
Last name: Velasquez, First name: Jose, Age: 72
Last name: Lamarque, First name: Henry, Age: 54
Last name: Vang, First name: Minh, Age: 22
Last name: Creswell, First name: Lucinda, Age: 18
Found Last name: Stimson, First name: Henry, Age: 29
Deleting Smith, Yee, and Creswell
Last name: Evans, First name: Patty, Age: 24
Last name: Adams, First name: Henry, Age: 63
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Stimson, First name: Henry, Age: 29
Last name: Velasquez, First name: Jose, Age: 72
Last name: Lamarque, First name: Henry, Age: 54
Last name: Vang, First name: Minh, Age: 22
classDataArray.java ,
,
. ( : , -
,
, .)

O-
:
, , .. -

.
. -
O-.
, -
,
. ?
-
. , 50%
,
. (
) .
, .
80 2.

:

-
, .
a[nElems], nElems
.
N . ,
T K:
T = K.
(
) , -
. K
. K
, . (
.)

: N
, -

. , N ,
T N:
T = K N/2.
, K
(, ) N.
T K,
T N. -
, 2 K; K ,
2. :
T = K N.
, -
. ,
.

:
log(N)
, T N :
T = K log2(N).
O- 81

, N 2.
-
( 3,322 ),
K; , -
:
T = K log(N).


O- , ,
K.
;
T N, .
, .

O
-
O
; , -
(Order of). O-
O(N), O(log N).
O(1), (
1).
2.5 , -
, O-.

2.5. O-
O-
O(N)
O(log N)
O(1)
O(N)
O(N)
O(N)

. 2.9
. (
) : O(1) , O(log N) , O(N)
, O(N2) . O(N2) -
,
.
O
- , -
.
,
.
82 2.

. 2.9.


?
,
?
. ,
O(1), O(N). -
O(N),
( ) .
, , -
, , , O(1),
O(log N). ,

.
83

,
new. ,
,
.
, . -
,
, .

.
, 5, .
, Java Vector, -
, .

.
.

, ,
, .
.

Java new.
, -
.
.
( ),
.
, -
.
.
A B () -
A B, 1.
, -
.
, -
.
O- .
, O(1), ;
O(log N) , O(N) O(N2) .
84 2.

.
.
1. :
a) , ;
b) ;
c) ;
d) .
2.

(/).
3. :
a) ;
b) ;
c) ;
d) .
4.
, (/).
5. Java
________.
6. A B - , :
a) A ;
b) , B ;
c) A;
d) B, .
7. A B - , B,
A, __________ B.
8. :
a) ;
b) ;
c) ;
d) .
9. , _____________ .
10. 1000 10 _____ .
11. , -
200 , :
a) 200;
b) 8;
85

c) 1;
d) 13.
12. 64 2 ______ .
13. 100 2 2 (/).
14. O- :
a) ;
b) ;
c) ;
d) .
15. O(1) , _________ .
16. ,
_________.

.
.
1. Array Workshop ,
. , , . -
, .
2. , , -
Ordered Workshop .
3. .
? -
Ordered Workshop.


,

.
2.1. HighArray highArray.java ( 2.3)
getMax(), 1,
. main() . ,
.
2.2. 2.1 ,
, .
removeMax().
86 2.

2.3. removeMax() 2.2


. , -
HighArray ( main()).
. ( -
,
3, .)
2.4. orderedArray.java ( 2.4) ,
insert() delete(), find() ( -
).
2.5. OrdArray orderedArray.java ( 2.4)
merge(), -
. main() ,
, merge()
. -
.
. ,
, .
2.6. HighArray highArray.java ( 2.3)
noDups(), . ,
17, noDups() .
.
-
null ( , ),
null. ,
.
3

- -
, . -
, , ,
, , ..
-
. 2, , ,
,
.

, -
.
. : -
, .
. 7,
, :
.
, ,
. , -
. , -
.
,
.
, -
.
.
, .
, , -
.

?
, (. 1, ) -
, .1.3. 9
. (
). ?
88 3.

. 3.1.

,
.
. ,
. ,
, .
(.3.2).

. 3.2. ,

.
, -
.
. , , ,
, , -
.
, , ,
, :
1. .
2. .
- .
89


, -
,
.


, ( )
.
? ,
N , 0 N1.
:
( 0) 0 1.
( 0) , . ,
. -
1 2. , ,
. .3.3.
:
1. .
2. , .
3. .
,
. ,
. :
, ,
( ) .
: -
, , . .3.4
, .
N1 0
N1 ( ).
.
-
. ,
.
, N2, (N1)
.
:
4. ,
.
, .
, ,
BubbleSort Workshop.
90 3.

. 3.3. :
91

. 3.4. :

BubbleSort Workshop
BubbleSort Workshop.
(.3.5).

. 3.5. BubbleSort Workshop

Run
: -
, .
, Run.
. -
( 10 )
, .3.6.
92 3.

. 3.6.

New
, New.
. -
New :
, .3.5, -
.
.

Step

BubbleSort

Workshop
-
. ,
.
New. -
, .
(inner inner+1) . outer
. ( inner
outer , .)
Step. inner inner+1
, .
,
.
, inner in-
ner+1, :
, .
93

,
. ( 10 45
22 ).
Step. , inner inner+1
0 outer, outer
. outer
, ( outer )
.

Size
Size (10 100 ). .3.7 -
, 100 .

. 3.7. Bubble Sort 100

, 100
( ). Run
, inner inner+1
,
.
. 3.8 .
( ) .
, .
Run -
- ,
Step. ,
Run .
94 3.

. 3.8. 100

Draw

, -
. , Draw, -
. ,
Run.


Java
bubbleSort.java, 3.1, ArrayBub -
a[], long. ,
, ,
. ( objectSort.java
3.4.) ,
find() delete() ArrayBub,
.

3.1. bubbleSort.java
// bubbleSort.java
//
// : C>java BubbleSortApp
////////////////////////////////////////////////////////////////
class ArrayBub
{
private long[] a; // a
95

private int nElems; //


//--------------------------------------------------------------
public ArrayBub(int max) //
{
a = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
a[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(a[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void bubbleSort()
{
int out, in;
for(out=nElems-1; out>1; out--) // ()
for(in=0; in<out; in++) // ()
if( a[in] > a[in+1] ) // ?
swap(in, in+1); //
}
//--------------------------------------------------------------
private void swap(int one, int two)
{
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
//--------------------------------------------------------------
} // ArrayBub
////////////////////////////////////////////////////////////////
class BubbleSortApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ArrayBub arr; //
arr = new ArrayBub(maxSize); //

arr.insert(77); // 10
arr.insert(99);

96 3.

3.1 ()
arr.insert(44);
arr.insert(55);
arr.insert(22);

arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

arr.display(); //

arr.bubbleSort(); //
arr.display(); //
} //
} // BubbleSortApp
////////////////////////////////////////////////////////////////
insert() display() ,
. bubbleSort().
.
main() 10 ,
, bubbleSort(), .
:
77 99 44 55 22 88 11 0 66 33
0 11 22 33 44 55 66 77 88 99
bubbleSort() :
public void bubbleSort()
{
int out, in;
for(out=nElems-1; out>1; out--) // ()
for(in=0; in<out; in++) // ()
if( a[in] > a[in+1] ) // ?
swap(in, in+1); //
}
-
( 0), ( nElems-1). out -
for ( nElems-1) -
. , out,
. out
, .
in
out.
, in in+1, in
in+1 .
97


swap(). ;
,
, -
. , swap()
, -
, .
, .

,
. .
.
;
.
bubbleSort.java ,
out . . ( -
, out ,
.)


,
BubbleSort
Workshop

10 -
, ,
. 10 :
9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45.
, N , -
N1 , N2 . .
:
(N1) + (N2) + (N3) + ... + 1 = N(N1)/2.
N=10, 45 (10 9/2).
, N2/2 ( 1
, N).
,
. -
,
N2/4. ( , -
, ).
, N2.
O

- , , -
O(N2).
, BubbleSort Workshop 100 .
98 3.

, (
), ,
O(N2). N , -
N ( N, -
). , NN, N2 .



O(N2)
O(N). , O(N2). -
-
, , -
, . (
Java, , .)


. -
, .
, - ; ,
.


-
( ) .
, (0). -
, . :
( ),
.
1,
1.
, .


.
.
, .
,
(
) . ,
. ,
.
, .
99

. 3.9.
100 3.

, .
. N1 , .

, -
. .3.9 ,
.

SelectSort Workshop
, ,
SelectSort

Workshop
. , Bub-

bleSort. New 10 .
outer ;
.
.
min ;
, ,
. ( min
.) inner ,
.
Step inner -
, ,
min. inner , min
, . inner ,
min .
outer, .

. 3.10. SelectSort Workshop


101

.3.10 .
outer , inner
. min
, outer.
Size, 100 -
, . , min
, ,
inner . outer
,
.


Java
selectSort.java bubbleSort.java,
ArraySel ArrayBub, bubbleSort() -
selectSort(). :
public void selectionSort()
{
int out, in, min;

for(out=0; out<nElems-1; out++) //


{
min = out; //
for(in=out+1; in<nElems; in++) //
if(a[in] < a[min] ) // min ,
min = in; // ,
swap(out, min); //
}
}
( out) ( 0)
. ( in)
out .
in a[in] a[min]. a[in]
, min in. min
,
, out min.
3.2 selectSort.java.

3.2. selectSort.java
// selectSort.java
//
// : C>java SelectSortApp
////////////////////////////////////////////////////////////////

102 3.

3.2 ()
class ArraySel
{
private long[] a; // a
private int nElems; //
//--------------------------------------------------------------
public ArraySel(int max) //
{
a = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
a[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(a[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void selectionSort()
{
int out, in, min;
for(out=0; out<nElems-1; out++) //
{
min = out; //
for(in=out+1; in<nElems; in++) //
if(a[in] < a[min] ) // min ,
min = in; // ,
swap(out, min); // swap them
}
}
//--------------------------------------------------------------
private void swap(int one, int two)
{
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
//--------------------------------------------------------------
}
////////////////////////////////////////////////////////////////
103

class SelectSortApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ArraySel arr; //
arr = new ArraySel(maxSize); //
arr.insert(77); // 10
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

arr.display(); //

arr.selectionSort(); //

arr.display(); //
}
} // SelectSortApp
////////////////////////////////////////////////////////////////
selectSort.java bubbleSort.java:
77 99 44 55 22 88 11 0 66 33
0 11 22 33 44 55 66 77 88 99

selectSort.java , -
out, .


,
: N (N1)/2. 10
45 , .
N , -
,
O(N2), . , -
- -
. N
,
.
104 3.


-
, .
O(N2), ,
. ,
, -
.
, .


-
. ,
.


- .
(, .)
; ,
. , -
, , ,
, .
:
. -
;
.


, ( -
), (.3.11, ).
(-
) .
, . -
(
) .3.11, .
,
. -
, . .
? ,
. ,
.
, ,
105

.
, -
. .3.11, .
,
. (-
) ,
. ,
( )
.

. 3.11.
106 3.

InsertSort Workshop
InsertSort Workshop .
, , 100 -
10 .

100
100 ( Size )
Run, . ,
outer -
. inner
outer,
. .3.12 , , -
.

. 3.12. InsertSort Workshop 100

,
,
, (
).

10
, 10--
Size. ( -
New, .)
inner outer -
( 1), outer temp.
107

. ( inner-1
, , inner.)
Step. outer temp.
, .
Java- ,
, .
, -
( ). , ,
.
, inner-1 inner.
,
temp. ;
. .3.13.
inner-1 inner, inner
. .
,
temp inner. ,
,
temp inner . ,
,
( ).

. 3.13. InsertSort Workshop 10

( -
), outer
, ( 2). . -
0, 1 2 ,
.
108 3.

. -
, ,
. , -

temp .


Java
insertSort.java
:
public void insertionSort()
{
int in, out;

for(out=1; out<nElems; out++) // out -


{
long temp = a[out]; //
in = out; // out
while(in>0 && a[in-1] >= temp) //
{
a[in] = a[in-1]; //
--in; //
}
a[in] = temp; //
}
}
for 1 .
. while
in out temp
, .
while -
.

InsertSort Workshop , .3.14 -
insertionSort() InsertSort

Work-

shop. 3.3 insertSort.java.

3.3. insertSort.java
// insertSort.java
//
// : C>java InsertSortApp
//--------------------------------------------------------------
class ArrayIns
{
private long[] a; // a
109

private int nElems; //


//--------------------------------------------------------------
public ArrayIns(int max) //
{
a = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
a[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(a[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void insertionSort()
{
int in, out;

for(out=1; out<nElems; out++) // out -


{
long temp = a[out]; //
in = out; // out
while(in>0 && a[in-1] >= temp) //
{
a[in] = a[in-1]; //
--in; //
}
a[in] = temp; //
}
}
//--------------------------------------------------------------
} // ArrayIns
////////////////////////////////////////////////////////////////
class InsertSortApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ArrayIns arr; //
arr = new ArrayIns(maxSize); //

arr.insert(77); // 10

110 3.

3.3 ()
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);

arr.display(); //

arr.insertionSort(); //

arr.display(); //
}
}
////////////////////////////////////////////////////////////////

. 3.14. - insertSort()
111

insertSort.java -
:
77 99 44 55 22 88 11 0 66 33
0 11 22 33 44 55 66 77 88 99


, temp, -
, outer, .


?
,
, N1 . :
1 + 2 + 3 + + N1 = N (N1)/2.
, -
(
), ; :
N N1)/4.

. , ,

. ,
,
O(N2).
, ,
. , while
; ,
, N1 .
O(N). ,
O(N), , -

.
,
,
.
, ( New)
InsertSort Workshop.
112 3.


, ,
long.
, . -
3.4 Java- objectSort.java,
Person (. classDataArray.java 2).

Java

Java
-
. Person
(lastName); . objectSort.java -
3.4.

3.4. objectSort.java
// objectSort.java
// ( )
// : C>java ObjectSortApp
////////////////////////////////////////////////////////////////
class Person
{
private String lastName;
private String firstName;
private int age;
//-----------------------------------------------------------
public Person(String last, String first, int a)
{ //
lastName = last;
firstName = first;
age = a;
}
//-----------------------------------------------------------
public void displayPerson()
{
System.out.print(" Last name: " + lastName);
System.out.print(", First name: " + firstName);
System.out.println(", Age: " + age);
}
//-----------------------------------------------------------
public String getLast() //
{ return lastName; }
} // Person
////////////////////////////////////////////////////////////////
class ArrayInOb
{
private Person[] a; // a
113

private int nElems; //


//--------------------------------------------------------------
public ArrayInOb(int max) //
{
a = new Person[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
//
public void insert(String last, String first, int age)
{
a[nElems] = new Person(last, first, age);
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
a[j].displayPerson(); //
System.out.println("");
}
//--------------------------------------------------------------
public void insertionSort()
{
int in, out;

for(out=1; out<nElems; out++) // out -


{
Person temp = a[out]; //
in = out; // out

while(in>0 && //
a[in-1].getLast().compareTo(temp.getLast())>0)
{
a[in] = a[in-1]; //
--in; //
}
a[in] = temp; //
}
}
//--------------------------------------------------------------
} // ArrayInOb
////////////////////////////////////////////////////////////////
class ObjectSortApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ArrayInOb arr; //

114 3.

3.4 ()
arr = new ArrayInOb(maxSize); //

arr.insert("Evans", "Patty", 24);


arr.insert("Smith", "Lorraine", 37);
arr.insert("Yee", "Tom", 43);
arr.insert("Adams", "Henry", 63);
arr.insert("Hashimoto", "Sato", 21);
arr.insert("Stimson", "Henry", 29);
arr.insert("Velasquez", "Jose", 72);
arr.insert("Lamarque", "Henry", 54);
arr.insert("Vang", "Minh", 22);
arr.insert("Creswell", "Lucinda", 18);

System.out.println("Before sorting:");
arr.display(); //
arr.insertionSort(); //

System.out.println("After sorting:");
arr.display(); //
}
} // ObjectSortApp
////////////////////////////////////////////////////////////////
:
Before sorting:
Last name: Evans, First name: Patty, Age: 24
Last name: Smith, First name: Doc, Age: 59
Last name: Smith, First name: Lorraine, Age: 37
Last name: Smith, First name: Paul, Age: 37
Last name: Yee, First name: Tom, Age: 43
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Stimson, First name: Henry, Age: 29
Last name: Velasquez, First name: Jose, Age: 72
Last name: Vang, First name: Minh, Age: 22
Last name: Creswell, First name: Lucinda, Age: 18
After sorting:
Last name: Creswell, First name: Lucinda, Age: 18
Last name: Evans, First name: Patty, Age: 24
Last name: Hashimoto, First name: Sato, Age: 21
Last name: Smith, First name: Doc, Age: 59
Last name: Smith, First name: Lorraine, Age: 37
Last name: Smith, First name: Paul, Age: 37
Last name: Stimson, First name: Henry, Age: 29
Last name: Vang, First name: Minh, Age: 22
Last name: Velasquez, First name: Jose, Age: 72
Last name: Yee, First name: Tom, Age: 43
115


insertSort() objectSort.java -
insertSort.java, -
lastName .
compareTo() String -
insertSort(). , , :
a[in-1].getLast().compareTo(temp.getLast()) > 0
compareTo()
( ) -
String, , String, .
. 3.1.
, s1 cat, s2 dog,
. objectSort.java
a[in-1] temp.

3.1. compareTo()
s2.compareTo(s1)
s1 < s2 <0
s1 = s2 0
s1 > s2 >0


,
. , -
. (
.) ,
,
. ,
. -
;
( ).
, , . ,
objectSort.java ( 3.4).
Smith. -
(Doc Smith, Lorraine Smith, Paul Smith),
.
116 3.


, ,
.
, . -
. ( ,
, 15,
.)
,
. -
, ,
.
-
. ,
.
; -
7.
.
.
, ,
.

.
(, bubbleSort.java)
. -
,
.

, ,
.
-
( , ),
.
O(N2). -
.
,
.
,
.
O(N2), ,
.
117

,
.

( -
).

.
.
1.
, ?
a) .
b) .
c) , , .
d) .
2. _________
_________ ( _________).
3.
(/).
4. :
a) ;
b) ;
c) ;
d) .
5. N NN
(/).
6. :
a) (
);
b) ;
c)
;
d) .
7.
, ,
(/).
8. ________ .
9. ?
118 3.

10. insertSort.java
, ?
a) in;
b) out;
c) temp;
d) a[out].
11. , :
a) , , ,
;
b) -
, ;
c) ;
d) , ,
, .
12.
__________.
13. , -
:
a) ;
b) ;
c) ;
d) , .
14. : ________.
15. , :
a) ;
b)
;
c) ;
d)
.

.
.
1. bubbleSort.java ( 3.1) main() ,
. -
:
119

for(int j=0; j<maxSize; j++) //


{ //
long n = (long)( java.lang.Math.random()*(maxSize-1) );
arr.insert(n);
}
10000 .
. display() ,
. -
, 100000 , ,
30 . , -
, .
selectSort.java ( 3.2) insertSort.java
( 3.3). .
2. ,
(99999, 99998, 99,997, ), bubbleSort.java.
, 1.
selectSort.java insertSort.java.
3. (0, 1, 2, )
bubbleSort.java. 1 2. -
selectSort.java insertSort.java.


,

.
3.1. bubbleSort.java ( 3.1)
BubbleSort
Work-

shop in ,
out . bubbleSort() ,
, , in ,
, ,
.
: ( out) .
3.2. ArrayIns insertSort.java ( 3.3)
median(), . (,
, .)
.
3.3. insertSort.java ( 3.3) noDups(),

. ( insertionSort()
main().) ,
-
120 3.

, O(N2)
. ,
-
O(N).
3.4. --
-
. a[j] a[j+1], j
(j = 1, 3, 5, ). ,
. (j=2,
4, 6, ). , -
. bubbleSort() bubbleSort.
java ( 3.1) - oddEvenSort().
, . ,
.
- -
,
( ) . -
, (
) .
.
3.5. insertionSort() insertSort.java ( 3.3),
,
. -
while.
,
.
O(N2)?
( ). -

?
3.6. . -
,
.
, ( . 2.6
2). insertionSort() insertSort.java,
. , -
,
(, 1, -
). ,
, 0.
. -
1 . .
( 1) -
. ,
0, .
4

: ,
. ,
. -
,
.


,
, , ,
. ,
.


, , , -
( , ..),
, .
, , -
.. ,
. :
, .
, , , -
.
,
. , .

; , .



( ), , -
. , -
122 4.

:
( , ).

. ( ) .

, -
, . ,
, : , -
. , ,
.
, ,
,
, . -

(ADT) 5, .

: ,
. ,
. . ,
. ,
,
.
() 3 (4 + 5).
, -
. 8, ,
, 13, ,
(,
).
.
,
. .
-
. ,
. -

.
123


.
.
, .
, ,
, ..
, ,
, .
( ). .4.1.
,

. 4.1.

, ,
.
, -
, .
, .
,
. -
.
. ,
124 4.

, .
.
-
. (A),
(B).
B

, -
(
C
). -
, (D).
D, C; C
B, B (-!)
A. ,
, .
()
, -
. , LIFO (Last-In-First-Out),
.

Stack Workshop
Stack Workshop , .
: New, Push, Pop Peek (.4.2).

. 4.2. Stack Workshop

Stack Workshop ,
. ,
. -
, , .
,
(, ).
125

New
Stack Workshop .
, , New .
.

Push
Push .
.
, .
,
. ,
( ) Top,
.
, Top.

.
,
. (
ADT
-
, .)

Pop
, Pop. -
Number;
pop().
:
, Top, Top
.
, Push.
Pop ,
( ).
,
. , Top
, ,
.
Top -
1 . , .
Cant pop:
stack is empty.

Peek
.

126 4.

. Peek , , Top
Number, .
: .
,
.


, , ;
, 10 . ,
,
. ,

1012 .

Java
stack.java StackX. 4.1
main() .
4.1. stack.java
// stack.java
//
// : C>java StackApp
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize; //
private long[] stackArray;
private int top; //
//--------------------------------------------------------------
public StackX(int s) //
{
maxSize = s; //
stackArray = new long[maxSize]; //
top = -1; //
}
//--------------------------------------------------------------
public void push(long j) //
{
stackArray[++top] = j; // top,
}
//--------------------------------------------------------------
public long pop() //
{
return stackArray[top--]; // , top
}
127

//--------------------------------------------------------------
public long peek() //
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // True,
{
return (top == -1);
}
//--------------------------------------------------------------
public boolean isFull() // True,
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class StackApp
{
public static void main(String[] args)
{
StackX theStack = new StackX(10); //
theStack.push(20); //
theStack.push(40);
theStack.push(60);
theStack.push(80);

while( !theStack.isEmpty() ) //
{ //
long value = theStack.pop();
System.out.print(value); //
System.out.print(" ");
}
System.out.println("");
}
} // StackApp
////////////////////////////////////////////////////////////////
main() StackApp 10 ,
4 , , ,
. :
80 60 40 20
. -
, 80
.
StackX long.
3, , ,
.
128 4.

StackX
, .
( ),
top, , . (-
: ,
. , ,
, .)
push() top, , -
, .
: top .

. 4.3. StackX

pop() , ,
top. , ,
; , (
, ).
peek() , .
129

isEmpty() isFull() true, -


. top 1, maxSize-1.
4.3 , .


. ,
-
?
-
. , ,
:
if( !theStack.isFull() )
insert(item);
else
System.out.print("Can't insert, stack is full");
main() ( -
, ,
). main() -
pop().
push() pop(). . Java
, , ,
.

1.

: .
, Enter. ,
.
.
,
.
LIFO
, -
, . reverse.java
4.2.

4.2. reverse.java
// reverse.java
//
// : C>java ReverseApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize;

130 4.

4.2 ()
private char[] stackArray;
private int top;
//--------------------------------------------------------------
public StackX(int max) //
{
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(char j) //
{
stackArray[++top] = j;
}
//--------------------------------------------------------------
public char pop() //
{
return stackArray[top--];
}
//--------------------------------------------------------------
public char peek() //
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // True,
{
return (top == -1);
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class Reverser
{
private String input; //
private String output; //
//--------------------------------------------------------------
public Reverser(String in) //
{ input = in; }
//--------------------------------------------------------------
public String doRev() //
{
int stackSize = input.length(); //
StackX theStack = new StackX(stackSize); //

for(int j=0; j<input.length(); j++)


{
char ch = input.charAt(j); //
theStack.push(ch); //
}
131

output = "";
while( !theStack.isEmpty() )
{
char ch = theStack.pop(); //
output = output + ch; //
}
return output;
}
//--------------------------------------------------------------
} // Reverser
////////////////////////////////////////////////////////////////
class ReverseApp
{
public static void main(String[] args) throws IOException
{
String input, output;
while(true)
{
System.out.print("Enter a string: ");
System.out.flush();
input = getString(); //
if( input.equals("") ) // , [Enter]
break;
// Reverser
Reverser theReverser = new Reverser(input);
output = theReverser.doRev(); //
System.out.println("Reversed: " + output);
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
} // ReverseApp
////////////////////////////////////////////////////////////////
Reverser .
doRev()
.
main() , Reverser
, doRev()
, -
. :
Enter a string: part
Reversed: trap
Enter a string:
132 4.

2.
.
, ,
, -.
,
, . -
Java- ( ),
Java. { },
[ ] ( ). ()
() , { -
} .. ,
, .
:
c[d] //
a{b[c]d}e //
a{b(c]d}e // ; ] (
a[b{c}d]e} // ; }
a{b(c) // ; {


-
.
,
. (,
),
. , ,
, - ,
.
, .
,
:
a{b(c[d]e)f}
4.1 ,
. ( ).
.
, , -
, .
. ;
.
, , ,
, LIFO.
133

4.1.

a
{ {
b {
( {(
c {(
[ {([
d {([
] {(
e {(
) {
f {
}

brackets.java Java
brackets.java 4.3.
check() BracketChecker.

4.3. brackets.java
// brackets.java
//
// : C>java BracketsApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize;
private char[] stackArray;
private int top;
//--------------------------------------------------------------
public StackX(int s) //
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(char j) //
{
stackArray[++top] = j;
}

134 4.

4.3 ()
//--------------------------------------------------------------
public char pop() //
{
return stackArray[top--];
}
//--------------------------------------------------------------
public char peek() //
{
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // True,
{
return (top == -1);
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class BracketChecker
{
private String input; //
//--------------------------------------------------------------
public BracketChecker(String in) //
{ input = in; }
//--------------------------------------------------------------
public void check()
{
int stackSize = input.length(); //
StackX theStack = new StackX(stackSize); //

for(int j=0; j<input.length(); j++) //


{
char ch = input.charAt(j); //
switch(ch)
{
case {: //
case '[':
case '(':
theStack.push(ch); //
break;

case }: //
case ']':
case ')':
if( !theStack.isEmpty() ) // ,
{
char chx = theStack.pop(); //
if( (ch=='} && chx!={) ||
(ch==']' && chx!='[') ||
135

(ch==')' && chx!='(') )


System.out.println("Error: "+ch+" at "+j);
}
else //
System.out.println("Error: "+ch+" at "+j);
break;
default: //
break;
}
}
//
if( !theStack.isEmpty() )
System.out.println("Error: missing right delimiter");
}//--------------------------------------------------------------
} // BracketChecker
////////////////////////////////////////////////////////////////
class BracketsApp
{
public static void main(String[] args) throws IOException
{
String input;
while(true)
{
System.out.print(
"Enter string containing delimiters: ");
System.out.flush();
input = getString(); //
if( input.equals("") ) // , [Enter]
break;
// BracketChecker
BracketChecker theChecker = new BracketChecker(input);
theChecker.check(); //
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
} // BracketsApp
////////////////////////////////////////////////////////////////
check() StackX reverse.java (. -
4.2). , :
. -
- .
136 4.

main() BracketsApp
, BracketChecker, ,
check() BracketChecker. -
, check() ;
.
check() , -
( 0 ) -
. ,
a{b(c]d}e
check() :
Error: ] at 5


, brackets.java.
, , -
,
. . -
push()/pop()
. (
, .)


, StackX, -
O(1). ,
; , ,
, .

, , ,
, (FIFO, First-In-First-
Out), , , ,
(
LIFO
). , : -
, , . ,
, ( ,
). .4.4 , .
, .
13 .
, -
: , .
137

. 4.4.

( )
, .
. , , -
. ,
, -
; ,
.
.

Queue Workshop
Queue Workshop , .

(.4.5).

. 4.5. Queue Workshop


138 4.

, .
, -
.

. , :
, , ,
.

Ins
Ins Queue Workshop
( ).
Number;
0 999.
, Rear .

Rem
Rem , -
. Number ( -
remove()), Front
. , ,
, , .
, ,
Front .
.4.6.
-
0. Front
, .4.7.
: .4.7 Front
Rear; , Front . ,
.

Peek
: -
, , .
Peek Front Number,
. peek() , -
.
rearPeek() frontPeek() (
), ,
, , .

New
, New.
139

. 4.6. Queue

. 4.7.
140 4.


-
.


Queue Workshop Front -
, .
Rear .
, .
,
. ,
,
.
, .
,
( ).
, , ,
Rear . -? -
.4.8.

. 4.8. Rear


,
, Front Rear -
141

.
( ).
Queue Workshop , .
, Rear
( 9). ( )
. Rear 9 0;
. .4.9.

. 4.9. Rear

. Rear , -
. : Rear
Front (, ).
.
, Rear .
, Front
Rear. .

Java
queue.java Queue. -
insert(), remove(), peek(), isFull(), isEmpty() size().
main() , -
, .
.
. :
40 50 60 70 80
142 4.

queue.java 4.4.

4.4. queue.java
// queue.java
//
// : C>java QueueApp
////////////////////////////////////////////////////////////////
class Queue
{
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;
//--------------------------------------------------------------
public Queue(int s) //
{
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
//--------------------------------------------------------------
public void insert(long j) //
{
if(rear == maxSize-1) //
rear = -1;
queArray[++rear] = j; // rear
nItems++; //
}
//--------------------------------------------------------------
public long remove() //
{
long temp = queArray[front++]; // front
if(front == maxSize) //
front = 0;
nItems--; //
return temp;
}
//--------------------------------------------------------------
public long peekFront() //
{
return queArray[front];
}
//--------------------------------------------------------------
public boolean isEmpty() // true,
{
return (nItems==0);
}
//--------------------------------------------------------------
public boolean isFull() // true,
143

{
return (nItems==maxSize);
}
//--------------------------------------------------------------
public int size() //
{
return nItems;
}
//--------------------------------------------------------------
} // Queue
////////////////////////////////////////////////////////////////
class QueueApp
{
public static void main(String[] args)
{
Queue theQueue = new Queue(5); // 5

theQueue.insert(10); // 4
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);

theQueue.remove(); // 3
theQueue.remove(); // (10, 20, 30)
theQueue.remove();

theQueue.insert(50); // 4
theQueue.insert(60); // ( )
theQueue.insert(70);
theQueue.insert(80);

while( !theQueue.isEmpty() ) //
{ //
long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n);
System.out.print(" ");
}
System.out.println("");
}
} // QueueApp
Queue
, nItems. -
;
.

insert()
insert() , . main() -
, insert() -
144 4.

isFull() . (
insert()
.)
rear,
, .
rear (maxSize-1),
. rear -
1, 0 (
). nItems.

remove()
remove() , . isEmpty() re-
move(), ,
remove().
front -
front. front ,
0.
.
nItems.

peek()
peek() : front. -
;
peekFront() peekRear() (
front() rear()).

isEmpty(), isFull() size()


isEmpty(), isFull() size() nItems.
0 maxSize,
.


nItems Queue
insert() remove(),
. , -
.
-
, / -
front rear. isEmpty(),
isFull() size() , -
, , , .
145

:
front rear ,
. .
, -
, .
4.5.

4.5.
class Queue
{
private int maxSize;
private long[] queArray;
private int front;
private int rear;
//--------------------------------------------------------------
public Queue(int s) //
{
maxSize = s+1; //
queArray = new long[maxSize]; //
front = 0;
rear = -1;
}
//--------------------------------------------------------------
public void insert(long j) //
{
if(rear == maxSize-1)
rear = -1;
queArray[++rear] = j;
}
//--------------------------------------------------------------
public long remove() //
{
long temp = queArray[front++];
if(front == maxSize)
front = 0;
return temp;
}
//--------------------------------------------------------------
public long peek() //
{
return queArray[front];
}
//--------------------------------------------------------------
public boolean isEmpty() // true,
{
return ( rear+1==front || (front+maxSize-1==rear) );
}
//--------------------------------------------------------------
public boolean isFull() // true,

146 4.

4.5 ()
{
return ( rear+2==front || (front+maxSize-2==rear) );
}
//--------------------------------------------------------------
public int size() // (assumes queue not empty)
{
if(rear >= front) //
return rear-front+1;
else //
return (maxSize-front) + (rear+1);
}
//--------------------------------------------------------------
} // Queue
isFull(), isEmpty() size(). -
,
.


, ,
O(1).

(deque) . ,
.
insertLeft()/insertRight() removeLeft()/removeRight().
insertLeft() removeLeft() ( -
), .
insertLeft() removeRight() ( ), .
, ; -
- .
, -
.


,
, .
, , , -
.
, ( )
. -
, .
147

-
. , ,
. -
( ),
, , (
), . -
- ; , -
. .
, (
); , .
.4.10.

. 4.10.

, , -
.
14, .
, ( ) -
. , -
, -
.

(
- )
. -
148 4.

,
.
,
. -
, ,
, (heap),
12.
. ;
, , ,
.

The PriorityQ Workshop


PriorityQ Workshop ,
.
,
, remove(). (
,
.)

( ),
0. .4.11 .
.

. 4.11. PriorityQ Workshop

Ins. -
Number. ,
. -
, .4.11 300.
Ins ,
149

.
.
.
: -
. -
, .
. ,
Rear ; 0
.

,
; , Front -
. , .
PriorityQ Workshop Front Rear -
, . ,
(nItems-1), -
, .
PriorityQ .4.12.

. 4.12. PriorityQ
150 4.


Peek (
), New .


, PriorityQ


Workshop
, -

.
( )

. , , , -
- .
( )
. , -
, , .
, -
, .
, , -
.

Java

Java
-
4.6.

4.6. priorityQ.java
// priorityQ.java
//
// : C>java PriorityQApp
////////////////////////////////////////////////////////////////
class PriorityQ
{
// ,
// a (0) (maxSize-1)
private int maxSize;
private long[] queArray;
private int nItems;
//-------------------------------------------------------------
public PriorityQ(int s) //
{
maxSize = s;
queArray = new long[maxSize];
nItems = 0;
}
//-------------------------------------------------------------
151

public void insert(long item) //


{
int j;

if(nItems==0) // ,
queArray[nItems++] = item; // 0
else //
{
for(j=nItems-1; j>=0; j--) //
{
if( item > queArray[j] ) // ,
queArray[j+1] = queArray[j]; //
else // ,
break; //
}
queArray[j+1] = item; //
nItems++;
}
} //
//-------------------------------------------------------------
public long remove() //
{ return queArray[--nItems]; }
//-------------------------------------------------------------
public long peekMin() //
{ return queArray[nItems-1]; }
//-------------------------------------------------------------
public boolean isEmpty() // true,
{ return (nItems==0); }
//-------------------------------------------------------------
public boolean isFull() // true,
{ return (nItems == maxSize); }
//-------------------------------------------------------------
} // PriorityQ
////////////////////////////////////////////////////////////////
class PriorityQApp
{
public static void main(String[] args) throws IOException
{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);

while( !thePQ.isEmpty() )
{
long item = thePQ.remove();
System.out.print(item + " "); // 10, 20, 30, 40, 50
}
152 4.

System.out.println("");
}
//-------------------------------------------------------------
} // PriorityQApp
main()
, . -
, :
10, 20, 30, 40, 50
insert() , ;
, 0. -

, , . -
, nItems .
, ,
isFull() insert().
front rear ( ),
, , front nItems-1, -
rear 0.
remove() : nItems ,
. peekMin() ,
, nItems. isEmpty() isFull() ,
nItems 0 maxSize .



O(N), O(1). 12 ,
.


, .
.
( )
2+3, 2(3+4), ((2+4)7)+3(95).
. brackets.java (. 4.3)
. -
( )
.
- -
. ,

(, , ).
, ,
153

. -
, .
,
( ).
:
1. ,
.
2. .
1 , 2 .
,
. , -
.
.
1 2, -
.


(+, , * /) -
(
). , ,
. 2+2, 47, A+B
A/B.
, , RPN
(Reverse Polish Notation), ,
. , A+B
AB+, A/B AB/.
; . 4.2.
, .

4.2.


A+BC AB+C
A*B/C AB*C/
A+B*C ABC*+
A*B+C AB*C+
A*(B+C) ABC+*
A*B+C*D AB*CD*+
(A+B)*(CD) AB+CD*
((A+B)*C)D AB+C*D
A+B*(CD/(E+F)) ABCDEF+/*+
154 4.


( ^), -
.
, ,
: +AB AB+.
, .

-
. ,
, - . ,
,
. , , -
, 14
234+, 2(3+4). (
, ,
).



?
: -
? , ,
.
3+4+5 3(4+5).
,
.
, -
:
1. . ( ,
. , ,
, .)
3. , ,
-
. (,
.)
4. ,
, .
4.34.5
. . 4.64.8 , -
155

-
.
3+45, -
. 4.3.

4.3. 3+45


3 3

3+ 3+

4 3+4

7
3+4.
7

5 75

2
75.

3+4 , , -
4. * /, +
* /.
4 ,
+. , ,
3+4 7. , 3+4 7.
75 .
.4.13 . : -
,
,
--.
- 3+45 -
. . 4.4.

4.4. 3+45


3 3

+ 3+

4 3+4

* 3+4 3+4 , -
* -
, +

156 4.

4.4 ()


5 3+45 5 -
3+20 45.
23
3+20

3+4 45. -
? , .
, * / , + ,
-
(
, ).

. 4.13. 3+45

, -
. --
157

(, A

+
B
) ,
B
-
, + ( )
. 5 ,
, 5 *
/. , , , -
5. , 5 ,
, . .4.14.

. 4.14. 3 + 4 5

. -
4.5 3 (4 + 5).
, .
,
.
,
3 4 4.
* /,

. ,
. 4 + 5 9; ,
39 27. ,
. .4.15.
158 4.

4.5. 3 (4 + 5)


3 3

* 3

( 3(

4 3 (4 3 4 -
+ 3 (4 +

5 3 (4 + 5 4 + 5 .
) 3 (4 + 5) ) 4 + 5.
39 4 + 5
27 39.

. 4.15. 3 (4 + 5)

,
-
. .
159

, ,
,
.
, .
, ,
() .
, -
, , ,
.



, .
;
. , -
.
.
, , -
.
. , ,
.
,
. ,

A
, . -
, ,
.
,
.
,
( ), -
.
4.6
A+BC .
. 4.3 -
3 + 4 5. , . 4.3
, .
. 4.7 A + B C
. 3 + 4 5
. 4.4.
4.8
A (B + C) .
3 (4 + 5) . 4.5.
.
160 4.

4.6. A + B C
, -



A A A

+ A+ A

B A+B AB

A+B AB +
+
.
C A+BC AB + C

A+BC AB + C
.

4.7. A + B C
, - -



A A A

+ A+ A

B A+B AB

A+B AB + ,
-
, +
C A+BC ABC C

-
A+BC ABC
A+BC ABC +
+

4.8. A (B C)
, - -



A A A

A A

( A( A

B A (B AB -

161

, - -



+ A (B + AB

C A (B + C ABC +
) A (B + C) ABC + ) +
A (B + C) ABC + + -

A (B + C) ABC +

, -
.
,
() -
-
.


. 4.7, . 4.8
.
, -
,
. , -
. . 4.9
A+B(CD) . (
) .

4.9. A + B (C D)
, - -



A A A

+ A+ A +
B A+B AB +
A+B AB +
( A+B( AB +(
C A + B (C ABC +(
A + B (C ABC +(
D A + B (C D ABCD +(

162 4.

4.9 ()
, - -



) A + B (C D) ABCD +(
A + B (C D) ABCD +(
A + B (C D) ABCD +
A + B (C D) ABCD +
A + B (C D) ABCD +

, -
+, -
+. , ,
+, , , .
, -
.
. 4.9 -
.
-
( ) .
,
. ,

. (A, B ..)
, -
; .



. , -
, . 4.10.
.

4.10.
,
()
()
(
) :
,
(, .
)
163

,
()
(opThis) ,
opThis

:
,
(, ,
(opTop),
opTop < opThis, opTop,
opTop >= opThis, opTop
.
, opTop

< opThis

, -
(.
opThis
,
,

< >= ,
. opThis
, opTop .
, . . 4.11
4.13 , .
. 4.64.8, ,
.
.

4.11. A + B C
, - -

-


A A A

+ A+ A + , opThis
B A+B AB +

A+B AB ,
A+B AB + opTop (+) >= opThis (),
A+B AB + opTop
opThis
C A+BC AB + C

A+BC AB + C , -

164 4.

4.12. A + B C
, - -

-


A A A
.
+ A+ A + , opThis.
B A+B AB +

A+B AB + , opTop.
A+B AB + opTop (+) < opThis (),
A+B AB + opTop.
opThis.
C A+BC ABC +
.
A+BC AB + , -
A+BC ABC + .
, -

4.13. A (B + C)
, - -

-


A A A

A A , opThis
( A( A ( (
B A (B AB (

+ A (B + AB , .
A (B + AB ( (, .
A (B + AB (+ opThis
C A (B + C ABC (+

) A (B + C) ABC + ( , -
A (B + C) ABC + .
, -
(
A (B + C) ABC + , -

165


Java
4.7 infix.java, .4.10
.

4.7. infix.java
// infix.java
//
// : C>java InfixApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize;
private char[] stackArray;
private int top;
//--------------------------------------------------------------
public StackX(int s) //
{
maxSize = s;
stackArray = new char[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(char j) //
{ stackArray[++top] = j; }
//--------------------------------------------------------------
public char pop() //
{ return stackArray[top--]; }
//--------------------------------------------------------------
public char peek() //
{ return stackArray[top]; }
//--------------------------------------------------------------
public boolean isEmpty() // true,
{ return (top == -1); }
//-------------------------------------------------------------
public int size() //
{ return top+1; }
//--------------------------------------------------------------
public char peekN(int n) // n
{ return stackArray[n]; }
//--------------------------------------------------------------
public void displayStack(String s)
{
System.out.print(s);
System.out.print("Stack (bottom-->top): ");
for(int j=0; j<size(); j++)

166 4.

4.7 ()
{
System.out.print( peekN(j) );
System.out.print(' ');
}
System.out.println("");
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class InToPost //
{
private StackX theStack;
private String input;
private String output = "";
//--------------------------------------------------------------
public InToPost(String in) //
{
input = in;
int stackSize = input.length();
theStack = new StackX(stackSize);
}
//--------------------------------------------------------------
public String doTrans() //
{
for(int j=0; j<input.length(); j++)
{
char ch = input.charAt(j);
theStack.displayStack("For "+ch+" "); // **
switch(ch)
{
case '+': // + -
case -:
gotOper(ch, 1); //
break; // ( 1)
case *: // * /
case /:
gotOper(ch, 2); //
break; // ( 2)
case (: //
theStack.push(ch); //
break;
case ): //
gotParen(ch); //
break;
default: //
output = output + ch; //
break;
}
}
167

while( !theStack.isEmpty() ) //
{
theStack.displayStack("While "); // **
output = output + theStack.pop(); // write to output
}
theStack.displayStack("End "); // **
return output; //
}
//--------------------------------------------------------------
public void gotOper(char opThis, int prec1)
{ //
while( !theStack.isEmpty() )
{
char opTop = theStack.pop();
if( opTop == '(' ) // '('
{
theStack.push(opTop); // '('
break;
}
else //
{
int prec2; //
if(opTop==+ || opTop==-) //
prec2 = 1;
else
prec2 = 2;
if(prec2 < prec1) //
{ //
theStack.push(opTop); //
break;
}
else //
output = output + opTop; //
}
}
theStack.push(opThis); //
}
//--------------------------------------------------------------
public void gotParen(char ch)
{ //
while( !theStack.isEmpty() )
{
char chx = theStack.pop();
if( chx == ( ) // (
break; //
else //
output = output + chx; //
}
}

168 4.

4.7 ()
//--------------------------------------------------------------
} // InToPost
////////////////////////////////////////////////////////////////
class InfixApp
{
public static void main(String[] args) throws IOException
{
String input, output;
while(true)
{
System.out.print("Enter infix: ");
System.out.flush();
input = getString(); //
if( input.equals("") ) // , [Enter]
break;
// -
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans(); //
System.out.println("Postfix is " + output + '\n');
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
} // InfixApp
////////////////////////////////////////////////////////////////
main() InfixApp -
. readString(). -
InToPost, ,
doTrans() .
, .
. 4.10 switch
doTrans(). gotOper() , -
) gotParen().
, .
StackX displayStack()
. ; ,
, .
169


. infix.java:
Enter infix: A*(B+C)-D/(E+F)
For A Stack (bottom-->top):
For * Stack (bottom-->top):
For ( Stack (bottom-->top): *
For B Stack (bottom-->top): * (
For + Stack (bottom-->top): * (
For C Stack (bottom-->top): * ( +
For ) Stack (bottom-->top): * ( +
For - Stack (bottom-->top): *
For D Stack (bottom-->top): -
For / Stack (bottom-->top): -
For ( Stack (bottom-->top): - /
For E Stack (bottom-->top): - / (
For + Stack (bottom-->top): - / (
For F Stack (bottom-->top): - / ( +
For ) Stack (bottom-->top): - / ( +
While Stack (bottom-->top): - /
While Stack (bottom-->top): -
End Stack (bottom-->top):
Postfix is ABC+*DEF+/-
, displayStack() (
for, while ), for
.

A

B
(-
, 3 7) . :
Enter infix: 2+3*4
For 2 Stack (bottom-->top):
For + Stack (bottom-->top):
For 3 Stack (bottom-->top): +
For * Stack (bottom-->top): +
For 4 Stack (bottom-->top): + *
While Stack (bottom-->top): + *
While Stack (bottom-->top): +
End Stack (bottom-->top):
Postfix is 234*+
, 234 2, 3 4.
infix.java .
,
, . .
, -
, .
.
170 4.


,
. ? ,
.
, , ,
.


.4.16 , ,
.

3 4 5 + * 6 1 2 + / -
9 3

27 2

25

. 4.16. 345+*612+/-

.
. , -
.
4 + 5 9.
,
. -
, (3 9 = 27).
, : 1 + 2 = 3, 6/3 = 2.
: 27 2 = 25.



, ?
, -
, .
, (
,
). -
. 4.14.
,
. ! -
.4.16.
171

4.14.
,



.


Java

(A, B ..). ,
, .
,
. -
, . -
, .
.
, .
:
Enter postfix: 57+
5 Stack (bottom-->top):
7 Stack (bottom-->top): 5
+ Stack (bottom-->top): 5 7
Evaluates to 12
.
.
, ( )
. infix.java,
displayStack(). postfix.java
4.8.

4.8. postfix.java
// postfix.java
//
// : C>java PostfixApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize;
private int[] stackArray;
private int top;

172 4.

4.8 ()
//--------------------------------------------------------------
public StackX(int size) //
{
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(int j) //
{ stackArray[++top] = j; }
//--------------------------------------------------------------
public int pop() //
{ return stackArray[top--]; }
//--------------------------------------------------------------
public int peek() //
{ return stackArray[top]; }
//--------------------------------------------------------------
public boolean isEmpty() // true,
{ return (top == -1); }
//--------------------------------------------------------------
public boolean isFull() // true,
{ return (top == maxSize-1); }
//--------------------------------------------------------------
public int size() //
{ return top+1; }
//--------------------------------------------------------------
public int peekN(int n) // n
{ return stackArray[n]; }
//--------------------------------------------------------------
public void displayStack(String s)
{
System.out.print(s);
System.out.print("Stack (bottom-->top): ");
for(int j=0; j<size(); j++)
{
System.out.print( peekN(j) );
System.out.print(' ');
}
System.out.println("");
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class ParsePost
{
private StackX theStack;
private String input;
//--------------------------------------------------------------
public ParsePost(String s)
173

{ input = s; }
//--------------------------------------------------------------
public int doParse()
{
theStack = new StackX(20); //
char ch;
int j;
int num1, num2, interAns;

for(j=0; j<input.length(); j++) //


{
ch = input.charAt(j); //
theStack.displayStack(""+ch+" "); // **
if(ch >= 0 && ch <= 9) //
theStack.push( (int)(ch-0) ); //
else //
{
num2 = theStack.pop(); //
num1 = theStack.pop();
switch(ch) //
{ //
case +:
interAns = num1 + num2;
break;
case '-':
interAns = num1 - num2;
break;
case '*':
interAns = num1 * num2;
break;
case '/':
interAns = num1 / num2;
break;
default:
interAns = 0;
}
theStack.push(interAns); //
} //
}
interAns = theStack.pop(); //
return interAns;
}
} // ParsePost
////////////////////////////////////////////////////////////////
class PostfixApp
{
public static void main(String[] args) throws IOException
{
String input;

174 4.

4.8 ()
int output;

while(true)
{
System.out.print("Enter postfix: ");
System.out.flush();
input = getString(); //
if( input.equals("") ) // ,
break; // [Enter]
//
ParsePost aParser = new ParsePost(input);
output = aParser.doParse(); //
System.out.println("Evaluates to " + output);
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
} // PostfixApp
////////////////////////////////////////////////////////////////
main() PostfixApp
ParsePost, .
doParse() ParsePost .
doParse() .
, ; , -
. (
, .)
. -
( )
.
: -
345 + 612+/,
.4.16. 3 (4 + 5) 6/(1 +2).
( -
: A (B + C) D/(E + F)
ABC +
DEF
+/ .) -
postfix.java:
Enter postfix: 345+*612+/-
3 Stack (bottom-->top):
4 Stack (bottom-->top): 3
175

5 Stack (bottom-->top): 3 4
+ Stack (bottom-->top): 3 4 5
* Stack (bottom-->top): 3 9
6 Stack (bottom-->top): 27
1 Stack (bottom-->top): 27 6
2 Stack (bottom-->top): 27 6 1
+ Stack (bottom-->top): 27 6 1 2
/ Stack (bottom-->top): 27 6 3
- Stack (bottom-->top): 27 2
Evaluates to 25
postfix.java, infix.java (. 4.7),
. , -
.
. -

, .

,
.
.
, .
()
, .
, .
-
.
( -
),
.
( -
) .

.
(-
, ).
,
.
.
176 4.

-
.

,
.

.
.
1. 10, 20, 30 40, -
. ?
2. ?
a) ,
.
b) , .
c) .
d) , -
.
3. LIFO FIFO?
4. -
(/).
5. , ,
0. , -
. , , 1,
. :
a)
;
b) -
;
c) ;
d)
.
6.
: -
?
7. 15, 25, 35 45,
. ?
177

8. / / -
O(N).
9. :
a) , ;
b) ;
c) , ;
d) .
10. -
( O-)?
11. , :
a) ;
b) -
;
c) ;
d) .
12. priorityQ.java ( 4.6)
(/).
13. :
a) ,
;
b) , -
;
c) -
, ;
d) .
14. , OrdArray
orderedArray.java ( 2.4 2, ).
.
OrdArray -
?
15. :
a) , ;
b) ;
c) ;
d) .
178 4.

.
.
1. Queue Workshop.
. (
.) -
, ,
.
2. PriorityQ Workshop, Front
Rear .
, ?
3. , .
, ?
?
-
?


,

.
4.1. Queue queue.java (. 4.4)
. , -
.
, , -
.
,
front rear.
4.2. Deque ( )
. insertLeft(), insertRight(), removeLeft(),
r emoveRight(), isEmpty() isFull().
, .
4.3. Deque . 4.2. -
, StackX
stack.java (. 4.1).
4.4. 4.6
, -
.
PriorityQ, ( O(1)) -
.
(. . 4.1).
179

4.5. , ,
, .. ,
, Queue queue.
java (. 4.4).
; display() . 4.1. -
. ,
.
( ).
.
,
. (, Java
.)
5

2, , ,
. -
, . -
. ,
.
,
. ,
.
-
. ,
(, ).
, (

).
, -
, , -
(, ).
.
,
, , ,
( ). -
(ADT), ,
ADT

-
.


,
(, -
, Link).
, ,
. ( Link) -
; , ,
next. first.
.5.1.
181


first next next next next
Null

. 5.1.

Link. -
:
class Link
{
public int iData; //
public double dData; //
public Link next; //
}
(self-
referential), (next )
.
. ,
, , , , ,
. , -
:
class Link
{
public inventoryItem iI; //
public Link next; //
}


,
. .
Link
. ? ,
Link, , -
, Link?
, Java Link Link.
next Link , .
, .
, -
; ,
182 5.

.


, ,
. ,
,
, -
Link.
,
Java
-
(int, double ..) -
, .
,
7
3,14159.
double salary = 65000.00;

65000.00. ,

Link aLink = someLink;
a L i n k
someLink Link .
someLink - . -
;
. -
new:
Link someLink = new Link();
someLink -

, . -
-
. 5.2. (.5.2).
(, C++)
. C++
Link next;
Link. C

++ -
( Link
Link; ). C++
Java

; -
.


-
.
. ,
: .
LinkList Workshop 183

:
.
. , , .
, , .
. , ; -
. , ,
. ,
.
, , ,
.

LinkList Workshop

LinkList

Workshop
. -
,
. Array
Workshop
2 -
.
.5.3 LinkList Workshop .
13 .

. 5.3. LinkList Workshop

, 13 ? .
Ins 0 999.
(.5.4).

. , , ,
.
184 5.

. 5.4.

Ins ,
. -
-
.

Find . -
, -
. ,
, .
, . -
, ,
, .

.
Del. -
.
,

.
:
.
, -
,
;
.
185


LinkList

Workshop
, -
. . ,
, .


linkList.java .
:
.
.
.
, .
( , ,
.)
linkList.java, -
Link LinkList.

Link
Link, .
:
class Link
{
public int iData; //
public double dData; //
public Link next; //
// -------------------------------------------------------------
public Link(int id, double dd) //
{
iData = id; //
dData = dd; // (next
} // null)
// -------------------------------------------------------------
public void displayLink() //
{
System.out.print("{" + iData + ", " + dData + "} ");
}
} // Link
, displayLink() -
{22, 33.9}. ,
displayLink() ,
display(). , ,
.
current.display();
186 5.

, current Link,
LinkList - .
. next ,
null . (,
null.) null
, ,
, .
Link (iData ..) (public).
, ;
, . -

Link LinkList.
. -
( ),
(
), ,
. public
, . ,
Link
private.

LinkList
LinkList :
. first.
, .
next, first:
class LinkList
{
private Link first; //
// -------------------------------------------------------------
public void LinkList() //
{
first = null; //
}
// -------------------------------------------------------------
public boolean isEmpty() // true,
{
return (first==null);
}
// -------------------------------------------------------------
// ...
}
LinkList first null.
, , , -
.
first.
187

first null, .
, first .
isEmpty() .

insertFirst()
insertFirst() LinkList .
, first
. ,
next , -
first , .
.5.5.

. 5.5. : ;

insertFirst()
, . ,
:
//
public void insertFirst(int id, double dd)
{ //
Link newLink = new Link(id, dd);
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
}
188 5.

--> ,
( first) . (
, -
<--.) .5.5. ,
, .
.

deleteFirst()
deleteFirst() insertFirst().
, first (-
next ):
public Link deleteFirst() //
{ // (, )
Link temp = first; //
first = first.next; // : first-->
return temp; //
} //
,
.
, -
temp temp. .5.6 ,
first .


. 5.6. : ;


C
++ -
, .
- , . ? Java
- ; .
: deleteFirst() , .
, isEmpty().
189

displayList()
, first
. current ( ,
) . first,
.
current = current.next;
current ,
next . displayList():
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
next null -
. null?
, ,
.
while . .5.7 ,
current .

. 5.7. : current = current.next; current = current.next

displayList() displayLink() -
.
190 5.

linkList.java
5.1 linkList.java. ,
main(), .

5.1. linkList.java
// linkList.java
//
// : C>java LinkListApp
////////////////////////////////////////////////////////////////
class Link
{
public int iData; // ()
public double dData; //
public Link next; //
// -------------------------------------------------------------
public Link(int id, double dd) //
{
iData = id; //
dData = dd; // ('next'
} // null)
// -------------------------------------------------------------
public void displayLink() //
{
System.out.print("{" + iData + ", " + dData + "} ");
}
} // Link
////////////////////////////////////////////////////////////////
class LinkList
{
private Link first; //
// -------------------------------------------------------------
public LinkList() //
{
first = null; //
}
// -------------------------------------------------------------
public boolean isEmpty() // true,
{
return (first==null);
}
// -------------------------------------------------------------
//
public void insertFirst(int id, double dd)
{ //
Link newLink = new Link(id, dd);
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
}
191

// -------------------------------------------------------------
public Link deleteFirst() //
{ // (, )
Link temp = first; //
first = first.next; // : first-->
return temp; //
} //
// -------------------------------------------------------------
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // LinkList
////////////////////////////////////////////////////////////////
class LinkListApp
{
public static void main(String[] args)
{
LinkList theList = new LinkList(); //
theList.insertFirst(22, 2.99); //
theList.insertFirst(44, 4.99);
theList.insertFirst(66, 6.99);
theList.insertFirst(88, 8.99);

theList.displayList(); //

while( !theList.isEmpty() ) // ,
{
Link aLink = theList.deleteFirst(); //
System.out.print("Deleted "); //
aLink.displayLink();
System.out.println("");
}
theList.displayList(); //
}
} // LinkListApp
////////////////////////////////////////////////////////////////
main() , -
insertFirst() . while
deleteFirst(),
192 5.

, .
linkList.java:
List (first-->last): {88, 8.99} {66, 6.99} {44, 4.99} {22, 2.99}
Deleted {88, 8.99}
Deleted {66, 6.99}
Deleted {44, 4.99}
Deleted {22, 2.99}
List (first-->last):



.
, LinkList Workshop.
linkList2.java 5.2.

5.2. linkList2.java
// linkList2.java
//
// : C>java LinkList2App
////////////////////////////////////////////////////////////////
class Link
{
public int iData; // ()
public double dData; //
public Link next; //
// -------------------------------------------------------------
public Link(int id, double dd) //
{
iData = id;
dData = dd;
}
// -------------------------------------------------------------
public void displayLink() //
{
System.out.print("{" + iData + ", " + dData + "} ");
}
} // Link
////////////////////////////////////////////////////////////////
class LinkList
{
private Link first; //
// -------------------------------------------------------------
public LinkList() //
{
first = null; //
}
193

// -------------------------------------------------------------
public void insertFirst(int id, double dd)
{ //
Link newLink = new Link(id, dd);
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public Link find(int key) //
{ // (, )
Link current = first; // 'first'
while(current.iData != key) //
{
if(current.next == null) //
return null; //
else //
current = current.next; //
}
return current; //
}
// -------------------------------------------------------------
public Link delete(int key) //
{ // (, )
Link current = first; //
Link previous = first;
while(current.iData != key)
{
if(current.next == null)
return null; //
else
{
previous = current; //
current = current.next;
}
} //
if(current == first) // ,
first = first.next; // first
else //
previous.next = current.next; //
return current;
}
// -------------------------------------------------------------
public void displayList() //
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //

194 5.

5.2 ()
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // LinkList
////////////////////////////////////////////////////////////////
class LinkList2App
{
public static void main(String[] args)
{
LinkList theList = new LinkList(); //

theList.insertFirst(22, 2.99); // 4
theList.insertFirst(44, 4.99);
theList.insertFirst(66, 6.99);
theList.insertFirst(88, 8.99);

theList.displayList(); //

Link f = theList.find(44); //
if( f != null)
System.out.println("Found link with key " + f.iData);
else
System.out.println("Cant find link");

Link d = theList.delete(66); //
if( d != null )
System.out.println("Deleted link with key " + d.iData);
else
System.out.println("Cant delete link");

theList.displayList(); //
}
} // LinkList2App
////////////////////////////////////////////////////////////////
main() ,
. 44, -
66 . :
List (first-->last): {88, 8.99} {66, 6.99} {44, 4.99} {22, 2.99}
Found link with key 44
Deleted link with key 66
List (first-->last): {88, 8.99} {44, 4.99} {22, 2.99}
195

find()
find() displayList()
linkList.java. current, first, -
, current.next.
find() ,
. , .
find() , , -
null.

delete()
delete() ,
find().
(current), (previous).
- ,
(.5.8). , -
.

17
17 44
44 98
98 73
73


. 5.8. : ;

while, current
current.next, previous current.
, previous , current.
, next
next . -
, ,
first LinkList,
.
196 5.

first first.next, deleteFirst() linkList.java.


, , :
//
if(current == first) // ,
first = first.next; // first
else //
previous.next = current.next; //


, -
.
. , insertAfter()
.
.


-
: ,
. .5.9.

next next next next


first Null

last

. 5.9.


, . ,
, -
, .
(
) , -
. ,
;
.
5.3 firstLastList.java ,
. ( ,
, .)
197

5.3. firstLastList.java
// firstLastList.java
//
// : C>java FirstLastApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long d) //
{ dData = d; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
// -------------------------------------------------------------
} // Link
////////////////////////////////////////////////////////////////
class FirstLastList
{
private Link first; //
private Link last; //
// -------------------------------------------------------------
public FirstLastList() //
{
first = null; //
last = null;
}
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return first==null; }
// -------------------------------------------------------------
public void insertFirst(long dd) //
{
Link newLink = new Link(dd); //
if( isEmpty() ) // ,
last = newLink; // newLink <-- last
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public void insertLast(long dd) //
{
Link newLink = new Link(dd); //
if( isEmpty() ) // ,
first = newLink; // first --> newLink
else
last.next = newLink; // last --> newLink

198 5.

5.3 ()
last = newLink; // newLink <-- last
}
// -------------------------------------------------------------
public long deleteFirst() //
{ // (, )
long temp = first.dData;
if(first.next == null) //
last = null; // null <-- last
first = first.next; // first --> next
return temp;
}
// -------------------------------------------------------------
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // FirstLastList
////////////////////////////////////////////////////////////////
class FirstLastApp
{
public static void main(String[] args)
{ //
FirstLastList theList = new FirstLastList();

theList.insertFirst(22); //
theList.insertFirst(44);
theList.insertFirst(66);

theList.insertLast(11); //
theList.insertLast(33);
theList.insertLast(55);

theList.displayList(); //

theList.deleteFirst(); //
theList.deleteFirst();

theList.displayList(); //
}
} // FirstLastApp
////////////////////////////////////////////////////////////////
199


. . ( ,

.)
,
. -
, . :
List (first-->last): 66 44 22 11 33 55
List (first-->last): 22 11 33 55
: -
, .
FirstLastList. ,
, first last, -
. ,
, null.
insertLast()
. last.next
last (. 5.10).
.
, ,
. , isEmpty() -
true, insertFirst() last ,
insertLast() first.

. 5.10. : ;
200 5.

insertFirst() first
; insertLast() -
last.
( last
null).
, -


-
, next null.
,
. (, -
, .)


. -
, O(1).
,
, O(N) .
O(N),
, -
. ,
, .
-
, ,
, .
-
( )
( ). ( -
) ,
,
. , ,
.


, : -
(ADT, Abstract Data Types). ADT? ,
: ,
, , .
.
, , .
, ,
201

. -
,
.


4, ,
Java. push() pop()
,
arr[++top] = data;

data = arr[top--];
( ).
. push()
pop() ,
theList.insertFirst(data)

data = theList.deleteFirst()
push() pop() -
. ( ),
. 5.4
LinkStack,
LinkList.

5.4. linkStack.java
// linkStack.java
//
// : C>java LinkStackApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long dd) //
{ dData = dd; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
} // Link
////////////////////////////////////////////////////////////////
class LinkList
{
private Link first; //

202 5.

5.4 ()
// -------------------------------------------------------------
public LinkList() //
{ first = null; } //
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return (first==null); }
// -------------------------------------------------------------
public void insertFirst(long dd) //
{ //
Link newLink = new Link(dd);
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public long deleteFirst() //
{ // (, )
Link temp = first; //
first = first.next; // : first-->
return temp.dData; //
} //
// -------------------------------------------------------------
public void displayList()
{
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // LinkList
////////////////////////////////////////////////////////////////
class LinkStack
{
private LinkList theList;
//--------------------------------------------------------------
public LinkStack() //
{
theList = new LinkList();
}
//--------------------------------------------------------------
public void push(long j) //
{
theList.insertFirst(j);
}
//--------------------------------------------------------------
203

public long pop() //


{
return theList.deleteFirst();
}
//--------------------------------------------------------------
public boolean isEmpty() // true,
{
return ( theList.isEmpty() );
}
//--------------------------------------------------------------
public void displayStack()
{
System.out.print("Stack (top-->bottom): ");
theList.displayList();
}
//--------------------------------------------------------------
} // LinkStack
////////////////////////////////////////////////////////////////
class LinkStackApp
{
public static void main(String[] args)
{
LinkStack theStack = new LinkStack(); //

theStack.push(20); //
theStack.push(40);

theStack.displayStack(); //

theStack.push(60); //
theStack.push(80);

theStack.displayStack(); //

theStack.pop(); //
theStack.pop();

theStack.displayStack(); //
}
} // LinkStackApp
////////////////////////////////////////////////////////////////
main() , , -
, ,
.
. :
Stack (top-->bottom): 40 20
Stack (top-->bottom): 80 60 40 20
Stack (top-->bottom): 40 20
204 5.

. main()
LinkStackApp LinkStack, LinkStack
LinkList. - main()
LinkList .
, main() push() LinkStack,
insertFirst() LinkList -
. pop() delete-
First() , displayStack() displayList()
. ,
main(), LinkStack -
stack.java (. 4.1)
4.


ADT. 5.5 ,
.

5.5. linkQueue.java
// linkQueue.java
//
// : C>java LinkQueueApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long d) //
{ dData = d; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
// -------------------------------------------------------------
} // Link
////////////////////////////////////////////////////////////////
class FirstLastList
{
private Link first; //
private Link last; //
// -------------------------------------------------------------
public FirstLastList() //
{
first = null; //
last = null;
}
// -------------------------------------------------------------
205

public boolean isEmpty() // true,


{ return first==null; }
// -------------------------------------------------------------
public void insertLast(long dd) //
{
Link newLink = new Link(dd); //
if( isEmpty() ) // ,
first = newLink; // first --> newLink
else
last.next = newLink; // last --> newLink
last = newLink; // newLink <-- last
}
// -------------------------------------------------------------
public long deleteFirst() //
{ // (, )
long temp = first.dData;
if(first.next == null) //
last = null; // null <-- last
first = first.next; // first --> next
return temp;
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // FirstLastList
////////////////////////////////////////////////////////////////
class LinkQueue
{
private FirstLastList theList;
//--------------------------------------------------------------
public LinkQueue() //
{ theList = new FirstLastList(); } // 2-
//--------------------------------------------------------------
public boolean isEmpty() // true,
{ return theList.isEmpty(); }
//--------------------------------------------------------------
public void insert(long j) //
{ theList.insertLast(j); }
//--------------------------------------------------------------
public long remove() //
{ return theList.deleteFirst(); }

206 5.

5.5 ()
//--------------------------------------------------------------
public void displayQueue()
{
System.out.print("Queue (front-->rear): ");
theList.displayList();
}
//--------------------------------------------------------------
} // LinkQueue
////////////////////////////////////////////////////////////////
class LinkQueueApp
{
public static void main(String[] args)
{
LinkQueue theQueue = new LinkQueue();
theQueue.insert(20); //
theQueue.insert(40);

theQueue.displayQueue(); //

theQueue.insert(60); //
theQueue.insert(80);

theQueue.displayQueue(); //

theQueue.remove(); //
theQueue.remove();

theQueue.displayQueue(); //
}
////////////////////////////////////////////////////////////////
, , -
.
. :
Queue (front-->rear): 20 40
Queue (front-->rear): 20 40 60 80
Queue (front-->rear): 60 80
insert() remove() LinkQueue insertLast()
deleteFirst() FirstLastList. ,
queue.java (. 4.4) 4,
.
linkStack.java linkQueue.java ,
, -
. ,
. push()/pop() ,
, ,
.
207


, ? , ,
,
. ,
, . , -
, , .


?
, .


. - -
, int double. ,
.

: , , -
, . , int
Java 2147483648
+2147483647, +, , *, / .. -

; , ,
.
- -
. -
, .
, (
, , ), (
)
(, ). -
, int double,
Java +
add() sub().
,
. -
, . ,
: ()
, ().
, (, ..), -
, .
int,
.
208 5.


. -
-. , ,
, . ,
, ,
.
, -
, .
(), -
() -
. ,
. , ,
, , -
.

, . ,
,
. -
, , ,
.
,
push() pop() ( , ) , . -
( ) ,
push() pop(), ,
, .

. -
,
. push(), pop()
.

ADT
, , ,
: . ( )
,
.
; , ,
(, ).
ADT ,
. , -
209

, .
, . -
.



-
. - ,
, .
? ?
? ? -
. ,
, -
,
.
ADT
. , -
.
ADT
, -
, .
,
, -
. , N,
, -
.
.

, -
. ,
, . ,
ADT;
, (,
). ,
.
.


, , -
.
. , -
, .
. -
( ) ,
210 5.

find() delete(),
.
,
, .
(
)
( ).
, , -
.

: .
,
(. 12, ).
LinkList Workshop, ,
, . ,
, 20 -
New Sorted.
, (.5.11).

. 5.11. LinkList Workshop

Ins. , -
. ,
. ,
(.5.12).
Ins
. -
Find Del.
211

. 5.12.


Java
,
( -
, , .5.12).
, -
: next ,
next .
: -
. :
public void insert(long key) //
{
Link newLink = new Link(key); //
Link previous = null; //
Link current = first;
//
while(current != null && key > current.dData)
{ // key > current,
previous = current;
current = current.next; //
}
if(previous==null) //
first = newLink; // first --> newLink
else //
previous.next = newLink; // prev --> newLink
newLink.next = current; // newLink --> current
}
212 5.

,
next .
: current, ,
first. previous null;
, ,
.
while ,
, . -
, (current.dData)
(key); , -
.
while , current
null. ( next -
null), , (first null).
, while
, ; , .
, previous
null; first .
,
previous.next .
next current.
, current null, next
.

sortedList.java
sortedList.java ( 5.6) SortedList
insert(), remove() displayList(). insert() -
.

5.6. sortedList.java
// sortedList.java
//
// : C>java SortedListApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long dd) //
{ dData = dd; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
} // end class Link
213

////////////////////////////////////////////////////////////////
class SortedList
{
private Link first; //
// -------------------------------------------------------------
public SortedList() //
{ first = null; }
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return (first==null); }
// -------------------------------------------------------------
public void insert(long key) //
{
Link newLink = new Link(key); //
Link previous = null; //
Link current = first;
//
while(current != null && key > current.dData)
{ // key > current,
previous = current;
current = current.next; //
}
if(previous==null) //
first = newLink; // first --> newLink
else //
previous.next = newLink; // prev --> newLink
newLink.next = current; // newLink --> current
}
// -------------------------------------------------------------
public Link remove() //
{ // (, )
Link temp = first; //
first = first.next; // : first-->
return temp; //
} //
}
// -------------------------------------------------------------
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
} // SortedList
////////////////////////////////////////////////////////////////

214 5.

5.6 ()
class SortedListApp
{
public static void main(String[] args)
{ //
SortedList theSortedList = new SortedList();
theSortedList.insert(20); //
theSortedList.insert(40);

theSortedList.displayList(); //

theSortedList.insert(10); //
theSortedList.insert(30);
theSortedList.insert(50);

theSortedList.displayList(); //

theSortedList.remove(); //

theSortedList.displayList(); //
}
} // SortedListApp
////////////////////////////////////////////////////////////////
main() 20 40,
10, 30 50.
, , insert()
. -
, ,
. .
sortedList.java:
List (first-->last): 20 40
List (first-->last): 10 20 30 40 50
List (first-->last): 20 30 40 50



O(N) ( N/2),
. , -
O(1),
.
, ,
. ,
.
215


-
. ,
. -
, .
.

(. 3, ),
.
O(N2),
,
; N -
N2/4. :
. N2
, N2
.
5.7 listInsertionSort.java, -
link,
( ), .

5.7. listInsertionSort.java
// listInsertionSort.java
//
// : C>java ListInsertionSortApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long dd) //
{ dData = dd; }
// -------------------------------------------------------------
} // Link
////////////////////////////////////////////////////////////////
class SortedList
{
private Link first; //
// -------------------------------------------------------------
public SortedList() // ( )
{ first = null; } //
// -------------------------------------------------------------
public SortedList(Link[] linkArr) // ( - )
{ //
first = null; //
for(int j=0; j<linkArr.length; j++) //

216 5.

5.7 ()
insert( linkArr[j] ); //
}
// -------------------------------------------------------------
public void insert(Link k) // ( )
{
Link previous = null; //
Link current = first;
//
while(current != null && k.dData > current.dData)
{ // > current,
previous = current;
current = current.next; //
}
if(previous==null) //
first = k; // first --> k
else //
previous.next = k; // prev --> k
k.next = current; // k --> current
}
// -------------------------------------------------------------
public Link remove() //
{ // (assumes non-empty list)
Link temp = first; //
first = first.next; //
return temp; //
} //
// -------------------------------------------------------------
} // SortedList

////////////////////////////////////////////////////////////////
class ListInsertionSortApp
{
public static void main(String[] args)
{
int size = 10;
//
Link[] linkArray = new Link[size];

for(int j=0; j<size; j++) //


{ //
int n = (int)(java.lang.Math.random()*99);
Link newLink = new Link(n); //
linkArray[j] = newLink; //
}
//
System.out.print("Unsorted array: ");
for(int j=0; j<size; j++)
System.out.print( linkArray[j].dData + " " );
217

System.out.println("");
// ,
//
SortedList theSortedList = new SortedList(linkArray);

for(int j=0; j<size; j++) // links from list to array


linkArray[j] = theSortedList.remove();
//
System.out.print("Sorted Array: ");
for(int j=0; j<size; j++)
System.out.print(linkArray[j].dData + " ");
System.out.println("");
}
} // ListInsertionSortApp
////////////////////////////////////////////////////////////////
. -
:
Unsorted array: 59 69 41 56 84 15 86 81 37 35
Sorted array: 15 35 37 41 56 59 69 81 84 86
, -
.
SortedList Link
.
( main()).
insert().
Link long. Link -
. sortedList.java (. 5.6)
, insert() Link long, -
.
(
) , -
, .
, ,
.


:
( !).
-
.
current=current.next
, -
.
218 5.

. ,
. -
String, .
,
. ,
?
current ( ) , -
. ,
.
.
, . ,
.
, . -
.
.5.13.

next next next next


first Null
prev prev prev prev
last Null

. 5.13.

Link, ,
:
class Link
{
public long dData; //
public Link next; //
public link previous; //
...
}
,
:
. ,
- .
(
), , -
.
doublyLinked.java , -
doublyLinkedList.
219

, display,
. displayForward() displayList()
. displayBackward() ,

previous . ,
:
Link current = last; //
while(current != null) //
current = current.previous; //

DoublyLinkedList . insertFirst()
, insertLast() ,
insertAfter() .
, , insertFirst()
previous ,
next . , first
. .5.14.

. 5.14.

, first.previous last.
:
if( isEmpty() ) // ,
last = newLink; // newLink <-- last
220 5.

else
first.previous = newLink; // newLink <-- first
newLink.next = first; // newLink --> first
first = newLink; // first --> newLink
insertLast() ;
insertFirst().
insertAfter() -
. ,
. ;
, find() linkList2.java (. -
5.2). , ,
, current
. .5.15.

. 5.15.

, next
null, last . insertAfter(),
, :
if(current==last) //
{
newLink.next = null; // newLink --> null
last = newLink; // newLink <-- last
}
else //
{
newLink.next = current.next; // newLink --> next
// newLink <-- next
current.next.previous = newLink;
}
221

newLink.previous = current; // current <-- newLink


current.next = newLink; // current --> newLink
, ?
.
current.next.previous
previous , next cur-
rent.

: deleteFirst(), deleteLast() deleteKey().


; deleteKey()
current. , ,
next current.previous (, )
current.next (, ),
previous current.next current.previous.
current . .5.16 ,
, :
current.previous.next = current.next;
current.next.previous = current.previous;

. 5.16.

,
,
first last.
deleteKey() :
if(current==first) // ?
first = current.next; // first --> next
else //
// previous --> next
current.previous.next = current.next;

if(current==last) // ?
last = current.previous; // previous <-- last
222 5.

else //
// previous <-- next
current.next.previous = current.previous;

doublyLinked.java
5.8 doublyLinked.java
.

5.8. doublyLinked.java
// doublyLinked.java
//
// : C>java DoublyLinkedApp
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
public Link previous; //
// -------------------------------------------------------------
public Link(long d) //
{ dData = d; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
// -------------------------------------------------------------
} // Link
////////////////////////////////////////////////////////////////
class DoublyLinkedList
{
private Link first; //
private Link last; //
// -------------------------------------------------------------
public DoublyLinkedList() //
{
first = null; //
last = null;
}
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return first==null; }
// -------------------------------------------------------------
public void insertFirst(long dd) //
{
Link newLink = new Link(dd); //
if( isEmpty() ) // ,
last = newLink; // newLink <-- last
else
first.previous = newLink; // newLink <-- first
223

newLink.next = first; // newLink --> first


first = newLink; // first --> newLink
}
// -------------------------------------------------------------
public void insertLast(long dd) //
{
Link newLink = new Link(dd); //
if( isEmpty() ) // ,
first = newLink; // first --> newLink
else
{
last.next = newLink; // last --> newLink
newLink.previous = last; // last <-- newLink
}
last = newLink; // newLink <-- last
}
// -------------------------------------------------------------
public Link deleteFirst() //
{ // (, )
Link temp = first;
if(first.next == null) //
last = null; // null <-- last
else
first.next.previous = null; // null <-- next
first = first.next; // first --> next
return temp;
}
// -------------------------------------------------------------
public Link deleteLast() //
{ // (, )
Link temp = last;
if(first.next == null) //
first = null; // first --> null
else
last.previous.next = null; // previous --> null
last = last.previous; // previous <-- last
return temp;
}
// -------------------------------------------------------------
// dd key
public boolean insertAfter(long key, long dd)
{ // (, )
Link current = first; //
while(current.dData != key) //
{
current = current.next; //
if(current == null)
return false; //
}

224 5.

5.7 ()
Link newLink = new Link(dd); //

if(current==last) //
{
newLink.next = null; // newLink --> null
last = newLink; // newLink <-- last
}
else //
{
newLink.next = current.next; // newLink --> next
// newLink <-- next
current.next.previous = newLink;
}
newLink.previous = current; // current <-- newLink
current.next = newLink; // current --> newLink
return true; // ,
}
// -------------------------------------------------------------
public Link deleteKey(long key) //
{ // (, )
Link current = first; //
while(current.dData != key) //
{
current = current.next; //
if(current == null)
return null; //
}
if(current==first) // ; ?
first = current.next; // first --> next
else //
// previous --> next
current.previous.next = current.next;

if(current==last) // ?
last = current.previous; // previous <-- last
else //
// previous <-- next
current.next.previous = current.previous;
return current; //
}
// -------------------------------------------------------------
public void displayForward()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
225

current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
public void displayBackward()
{
System.out.print("List (last-->first): ");
Link current = last; //
while(current != null) //
{
current.displayLink(); //
current = current.previous; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // DoublyLinkedList
////////////////////////////////////////////////////////////////
class DoublyLinkedApp
{
public static void main(String[] args)
{ //
DoublyLinkedList theList = new DoublyLinkedList();

theList.insertFirst(22); //
theList.insertFirst(44);
theList.insertFirst(66);

theList.insertLast(11); //
theList.insertLast(33);
theList.insertLast(55);

theList.displayForward(); //
theList.displayBackward(); //

theList.deleteFirst(); //
theList.deleteLast(); //
theList.deleteKey(11); // 11

theList.displayForward(); //

theList.insertAfter(22, 77); // 77 22
theList.insertAfter(33, 88); // 88 33

theList.displayForward(); //
}
} // DoublyLinkedApp
////////////////////////////////////////////////////////////////
226 5.

main() , -
-
, 11.
( ), -
insertAfter(), .
:
List (first-->last): 66 44 22 11 33 55
List (last-->first): 55 33 11 22 44 66
List (first-->last): 44 22 33
List (first-->last): 44 22 77 33 88
insertAfter() , .
main() isEmpty(),
/.


,
(. ).
;
.

,
find().
, .
,
,
.
- .
, ,
, , -
(
). , , -
, .
, -
. -
, ,
, .
. -
? find()

.
227

, , ,
-
.

?
,
.
. -
,
.
, ; ?
-
( current - ). -
current, current
.
:
( -
).
, .
,
. -
.
, ,
.

,
, .
:
class ListIterator()
{
private Link current;
...
}
current , -
. (
C++; .)
, ,
-, .
,
, first. -
getIterator(), -
228 5.

. main(),
:
public static void main(...)
{
LinkList theList = new LinkList(); //
ListIterator iter1 = theList.getIterator(); //
Link aLink = iter1.getCurrent(); //
iter1.nextLink(); //
}
- , -
, (
). -
iter1 ,
(iter2 ..).
. ,
, . .5.17 -
, .

. 5.17.


, previous
, -
. .
, first
, .
229

,
( first)?
. -
.
, first. LinkList
getFirst() setFirst(). (
, first ,
.)
( )
, re-
set() nextLink():
class ListIterator()
{
private Link current; //
private Link previous; //
private LinkList ourList; // ""
public void reset() // set to start of list
{
current = ourList.getFirst(); // current --> first
previous = null; // previous --> null
}
public void nextLink() //
{
previous = current; // previous
current = current.next; // next
}
...
}
C++: C++

(friend) . Java
; , ,
.


. -
, (, insertAfter()),
, .
:
reset() .
nextLink() .
getCurrent() , .
atEnd() true, .
insertAfter() .
230 5.

insertBefore() .
deleteCurrent() .
reset() nex-
tLink(), atEnd(),
.
, ,
, . insertBefore() ,
insertFirst(), , -
. displayList() ,
getCurrent()
nextLink().

interIterator.java
interIterator.java -
.
:
s .
r .
n .
g .
b .
a .
d .
5.9 interIterator.java.

5.9
// interIterator.java
//
// : C>java InterIterApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class Link
{
public long dData; //
public Link next; //
// -------------------------------------------------------------
public Link(long dd) //
{ dData = dd; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(dData + " "); }
} // Link
////////////////////////////////////////////////////////////////
231

class LinkList
{
private Link first; //
// -------------------------------------------------------------
public LinkList() //
{ first = null; } //
// -------------------------------------------------------------
public Link getFirst() //
{ return first; }
// -------------------------------------------------------------
public void setFirst(Link f) // first
{ first = f; }
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return first==null; }
// -------------------------------------------------------------
public ListIterator getIterator() //
{
return new ListIterator(this); // this
}
// -------------------------------------------------------------
public void displayList()
{
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
// -------------------------------------------------------------
} // LinkList
////////////////////////////////////////////////////////////////
class ListIterator
{
private Link current; //
private Link previous; //
private LinkList ourList; //
//--------------------------------------------------------------
public ListIterator(LinkList list) //
{
ourList = list;
reset();
}
//--------------------------------------------------------------
public void reset() // 'first'
{
current = ourList.getFirst();

232 5.

5.9 ()
previous = null;
}
//--------------------------------------------------------------
public boolean atEnd() // true,
{ return (current.next==null); } //
//--------------------------------------------------------------
public void nextLink() //
{
previous = current;
current = current.next;
}
//--------------------------------------------------------------
public Link getCurrent() //
{ return current; }
//--------------------------------------------------------------
public void insertAfter(long dd) //
{ //
Link newLink = new Link(dd);

if( ourList.isEmpty() ) //
{
ourList.setFirst(newLink);
current = newLink;
}
else //
{
newLink.next = current.next;
current.next = newLink;
nextLink(); //
}
}
//--------------------------------------------------------------
public void insertBefore(long dd) //
{ //
Link newLink = new Link(dd);

if(previous == null) //
{ // ( )
newLink.next = ourList.getFirst();
ourList.setFirst(newLink);
reset();
}
else //
{
newLink.next = previous.next;
previous.next = newLink;
current = newLink;
}
}
233

//--------------------------------------------------------------
public long deleteCurrent() //
{
long value = current.dData;
if(previous == null) //
{
ourList.setFirst(current.next);
reset();
}
else //
{
previous.next = current.next;
if( atEnd() )
reset();
else
current = current.next;
}
return value;
}
//--------------------------------------------------------------
} // ListIterator
////////////////////////////////////////////////////////////////
class InterIterApp
{
public static void main(String[] args) throws IOException
{
LinkList theList = new LinkList(); //
ListIterator iter1 = theList.getIterator(); //
long value;

iter1.insertAfter(20); //
iter1.insertAfter(40);
iter1.insertAfter(80);
iter1.insertBefore(60);

while(true)
{
System.out.print("Enter first letter of show, reset, ");
System.out.print("next, get, before, after, delete: ");
System.out.flush();
int choice = getChar(); //
switch(choice)
{
case 's': //
if( !theList.isEmpty() )
theList.displayList();
else
System.out.println("List is empty");
break;

234 5.

5.9 ()
case r: //
iter1.reset();
break;
case n: //
if( !theList.isEmpty() && !iter1.atEnd() )
iter1.nextLink();
else
System.out.println("Cant go to next link");
break;
case g: //
if( !theList.isEmpty() )
{
value = iter1.getCurrent().dData;
System.out.println("Returned " + value);
}
else
System.out.println("List is empty");
break;
case b: //
System.out.print("Enter value to insert: ");
System.out.flush();
value = getInt();
iter1.insertBefore(value);
break;
case 'a': //
System.out.print("Enter value to insert: ");
System.out.flush();
value = getInt();
iter1.insertAfter(value);
break;
case 'd': //
if( !theList.isEmpty() )
{
value = iter1.deleteCurrent();
System.out.println("Deleted " + value);
}
else
System.out.println("Cant delete");
break;
default:
System.out.println("Invalid entry");
}
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
235

String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//-------------------------------------------------------------
} // InterIterApp
////////////////////////////////////////////////////////////////
main() ,
insertAfter(), .
, ,
, (
60), 100, 100
7 :
Enter first letter of
show, reset, next, get, before, after, delete: s
20 40 60 80
Enter first letter of
show, reset, next, get, before, after, delete: r
Enter first letter of
show, reset, next, get, before, after, delete: n
Enter first letter of
show, reset, next, get, before, after, delete: n
Enter first letter of
show, reset, next, get, before, after, delete: g
Returned 60
Enter first letter of
show, reset, next, get, before, after, delete: b
Enter value to insert: 100
Enter first letter of
show, reset, next, get, before, after, delete: a
Enter value to insert: 7
Enter first letter of
show, reset, next, get, before, after, delete: s
20 40 100 7 60 80
interIterator.java -
, /
.
236 5.

?
:

?
, deleteCurrent().
,
?
,
.
,
previous ( ).
, -
. ,
.
insertBefore() insertAfter() current, -
.

atEnd()
atEnd() . true,
,
(
).
,
, -
, ( , ).
, ,
, -
(, ). atEnd()
true, ( -
),
.
. -
, , ,
.


, -
, .
(
displayList() ):
iter1.reset(); //
long value = iter1.getCurrent().dData; //
237

System.out.println(value + " ");


while( !iter1.atEnd() ) //
{
iter1.nextLink(); //
long value = iter1.getCurrent().dData; //
System.out.println(value + " ");
}
, getCurrent()
isEmpty(), .
, 3.
main();
, interIterator.java (. 5.9).
class InterIterApp
{
public static void main(String[] args) throws IOException
{
LinkList theList = new LinkList(); //
ListIterator iter1 = theList.getIterator(); //

iter1.insertAfter(21); //
iter1.insertAfter(40);
iter1.insertAfter(30);
iter1.insertAfter(7);
iter1.insertAfter(45);

theList.displayList(); //

iter1.reset(); //
Link aLink = iter1.getCurrent(); //
if(aLink.dData % 3 == 0) // 3,
iter1.deleteCurrent(); // .
while( !iter1.atEnd() ) //
{
iter1.nextLink(); //

aLink = iter1.getCurrent(); //
if(aLink.dData % 3 == 0) // 3,
iter1.deleteCurrent(); // .
}
theList.displayList(); //
}
} // InterIterApp
.
, , 3, -
. :
21 40 30 7 45
40 7
, , deleteCurrent()
.
238 5.


,
ListIterator , find(),
( find() ), replace(),
.
, -
.
, .
.

linkedList
Link.
linkedList (
first).
Link
( next).
next null, .
,
next , first ,
first .
, first
first.next.
, first,
next .
.
, ,
.
, -
.
(
last) .
.
(ADT) , -
.
. -
, .

( ) .
239

O(N), -
.
O(1).
,
.
-
.
, ,
.
-
, .

- ( ) .

.
.
1. ? :
a) ;
b) , ;
c) ;
d) .
2.
_________ .
3. :
a) ;
b) , current;
c) , next;
d) .
4. -
?
5. -
?
6. insertFirst() linkList.java (. 5.1)
newLink.next=first; , :
a) first;
b) first ;
240 5.

c) next ,
.
d) newLink.next .
7. , current
. ?
8. , -
?
9. :
a) ;
b) ;
c) , , -
;
d) .
10. : ________
.
11. , ,
:
?
12.
?
13. , ,
?
14. ?
:
a) ;
b) ;
c) ;
d) .
15. , , :
?

.
.
1. LinkList Workshop ,
.
- , -
?
241

2. main() linkList.java (. 5.1) ,


-
.
, .
. (-
, , ,
.) ,
.


,

.
5.1.
.
.
5.2. (. 4.2
). .
5.3. ,
. -
.
. ,
, .
, , . -
current,
. ,
(, ,
5.5). , .
, , ,
current. ( , -
.)
(
). step(),
current , .
5.4. 5.3.
. (, ,
.)
5.5.
. , .
, ,
. .
, ,
242 5.

. n- -
. , , ,
. () 20
, ?
, .
,
( 5.3). -
, ,
( 1). .
, (-
, ). ,
1 7, 3 (
1), 4, 1, 6, 5, 7, 3. 2
.
5.6. :
, .
-
, . -
,
N M , , , .
,
N .
(
). ( -
) , -
. ,

.
(, 7 10).

.
6

, (-
) .
. -
-
. -
, .
,
.
,
.
, ,
,
, .
.
-
.


, ,
( )
1, 3, 6, 10, 15, 21, .
?
N- n . -
, , (1) 2; 1+2=3.
(3) 3; 3+3=6 . .
,
,
(.6.1).
244 6.

. 6.1.

n-
, n- -
, 4- (10). ? .6.2 ,
.

1
2
3
4
: 10

. 6.2.

,
.. 4 + 3 + 2 + 1 10.
triangle()
. n
1:
int triangle(int n)
{
int total = 0;

while(n > 0) // n 1
245

{
total = total + n; // total n ( )
--n; //
}
return total;
}
n . total
n, n 1 1. n 0,
.

n-

, -
. n-
( ):
1. ( ) n.
2. .
.6.3.

6
4
: 10

. 6.3.



, triangle(), n- ,
:
int triangle(int n)
{
return( n + sumRemainingColumns(n) ); // ( )
}
? sumRemainingColumns() ,
triangle().
: .6.3 n
n 1. , ,
246 6.

n,
n1 n:
int triangle(int n)
{
return( n + sumAllColumns(n-1) ); // ( )
}
, sumAllColumns() ,
triangle(): n, -
. triangle()?
:
int triangle(int n)
{
return( n + triangle(n-1) ); // ( )
}
, , , , ,
? ( )
. ,
.

. -
9- . , 9- 8- -
, 8-
. , 9
.
, 8- 8- 7-
. 7- .
, .
? -
, . , -
, -
, . triangle()
, , .


, -
(n=1), , 1
.
, .
triangle() :
int triangle(int n)
{
if(n==1)
return 1;
247

else
return( n + triangle(n-1) );
}
, -
, . -

.

triangle.java
triangle.java, , -
. n
. triangle.java 6.1.

6.1. triangle.java
// triangle.java
//
// : C>java TriangleApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class TriangleApp
{
static int theNumber;

public static void main(String[] args) throws IOException


{
System.out.print("Enter a number: ");
theNumber = getInt();
int theAnswer = triangle(theNumber);
System.out.println("Triangle="+theAnswer);
}
//-------------------------------------------------------------
public static int triangle(int n)
{
if(n==1)
return 1;
else
return( n + triangle(n-1) );
}
//-------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}

248 6.

6.1 ()
//--------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//--------------------------------------------------------------
} // TriangleApp
////////////////////////////////////////////////////////////////
main() ,
triangle() .
triangle(), .
:
Enter a number: 1000
Triangle = 500500
, triangle(),
:
n- = (n2+n)/2

?
triangle(), ,
.
:
public static int triangle(int n)
{
System.out.println("Entering: n=" + n);
if(n==1)
{
System.out.println("Returning 1");
return 1;
}
else
{
int temp = n + triangle(n-1);
System.out.println("Returning " + temp);
return temp;
}
}

triangle(), 5:
Enter a number: 5
Entering: n=5
Entering: n=4
249

Entering: n=3 n=5


Entering: n=2
Entering: n=1
Returning 1
1
Returning 3 n=5
Returning 6 2
Returning 10 n=4
Returning 15 3
n=3
Triangle = 15 4
n=2
, triangle()
, , 5, 5
1. , n=1
1
1,
.
2
. , 3
, .
3
n, - 6
, - 4
. 10

- 5
15
,
main(). .6.4 , -
triangle() -
15
.
, - . 6.4.
1, - triangle()
triangle(). -
5, 1.


triangle(), , -
:
.
.
, , -
.

( , , -
) .
,
, .
250 6.

?
-
. .
, ,
,
.
triangle() , -
.
,
. .

. -
.
,
, .



- . ( -
.)
:
tri(n) = 1 if n = 1
tri(n) = n + tri(n1) if n > 1
, - -
, (
).

, ,
. n
n1 n, n -
n1 n. ,
5+4+3+2+1, 5
54321 = 120. 6.1 10 .

6.1.

0 1
1 1*1 1
251


2 2*1 2
3 3*2 6
4 4*6 24
5 5 * 24 120
6 6 * 120 720
7 7 * 720 5040
8 8 * 5040 40320
9 9 * 40320 362880

0 1. , -
.
, -
triangle(). :
int factorial(int n)
{
if(n==0)
return 1; n=4

else
return (n * factorial(n-1) );
1
}
n=4
factorial() triangle() 2
. -, factorial() - n=3

* + 3
n=2
n * factorial(n-1) 4
n=1
-, factorial() -
, n 0, 1.
5
, n=0
triangle.java: 1

Enter a number: 6
1
Factorial =720
1
.6.5 , - 2
factorial() 2
n=4. 3
6
4
, - 24
, .

, -
24

( ), - . 6.5.
.. , - factorial()
252 6.

, ,
.

, -
.
. ,
, ( ,
). , cat
:
cat
cta
atc
act
tca
tac
. -
, . -
6 , 24,
120 .. (,
; .)
? -
n :
1. n1 .
2. n .
3. n .

. 6.6.
253


, (.6.6).
n ,
. ,
( -
). cat ,
.
. 6.2.

. -
cat, cta, cat.
.
n1 ? -
. doAnagram()
, . ,
n . , doAnagram() -
, (.6.7).

6.2. cat

?
cat c at at
cta c ta ta
cat c at cat
atc a tc tc
act a ct ct
atc a tc atc
tca t ca ca
tac t ac ac
tca t ca tca
cat c at

, , -
, . -
, .
, ,
. n ,
n . doAnagram():
public static void doAnagram(int newSize)
{
if(newSize == 1) // ,
return; // .
for(int j=0; j<newSize; j++) //
254 6.

{
doAnagram(newSize-1); //
if(newSize==2) //
displayWord(); //
rotate(newSize); //
}
}

. 6.7. doAnagram()

, doAnagram() ,
, (.6.8).
6.2 anagram.java. main() -
,
, doAnagram().
255

n e t s

0 1 2 3
4 newSize = 1
position = 3
3 newSize = 2
position = 2

2 newSize = 3
position = 1

1 newSize = 4
position = 0

. 6.8.

6.2. anagram.java
// anagram.java
//
// : C>java AnagramApp
import java.io.*;
////////////////////////////////////////////////////////////////
class AnagramApp
{
static int size;
static int count;
static char[] arrChar = new char[100];

public static void main(String[] args) throws IOException


{
System.out.print("Enter a word: "); //
String input = getString();
size = input.length(); //
count = 0;
for(int j=0; j<size; j++) //
arrChar[j] = input.charAt(j);
doAnagram(size); //
}
//-----------------------------------------------------------
public static void doAnagram(int newSize)
{
if(newSize == 1) // ,
return; // .
for(int j=0; j<newSize; j++) //
{
doAnagram(newSize-1); //
if(newSize==2) //
displayWord(); //
rotate(newSize); //
}
}

256 6.

6.2 ()
//-----------------------------------------------------------
// rotate left all chars from position to end
public static void rotate(int newSize)
{
int j;
int position = size - newSize;
char temp = arrChar[position]; //
for(j=position+1; j<size; j++) //
arrChar[j-1] = arrChar[j];
arrChar[j-1] = temp; //
} //
//-----------------------------------------------------------
public static void displayWord()
{
if(count < 99)
System.out.print(" ");
if(count < 9)
System.out.print(" ");
System.out.print(++count + " ");
for(int j=0; j<size; j++)
System.out.print( arrChar[j] );
System.out.print(" ");
System.out.flush();
if(count%6 == 0)
System.out.println("");
}
//-----------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
} // AnagramApp
////////////////////////////////////////////////////////////////
rotate() ,
. displayWord() ,
, .
:
Enter a word: cats
1 cats 2 cast 3 ctsa 4 ctas 5 csat 6 csta
7 atsc 8 atcs 9 asct 10 astc 11 acts 12 acst
13 tsca 14 tsac 15 tcas 16 tcsa 17 tasc 18 tacs
19 scat 20 scta 21 satc 22 sact 23 stca 24 stac
257

- -
. 6 720, -
, .


, 2, ? -

. , , -
,
. . find() :
public int find(long searchKey)
{
int lowerBound = 0;
int upperBound = nElems-1;
int curIn;

while(true)
{
curIn = (lowerBound + upperBound ) / 2;
if(a[curIn]==searchKey)
return curIn; //
else if(lowerBound > upperBound)
return nElems; //
else //
{
if(a[curIn] < searchKey)
lowerBound = curIn + 1; //
else
upperBound = curIn - 1; //
}
}
}
2,
, , . -
, Ordered Workshop
.
, ,
. -
lowerBound upperBound, .
() .
258 6.


lowerBound upperBound find()
lowerBound upperBound.
.
:
private int recFind(long searchKey, int lowerBound,
int upperBound)
{
int curIn;

curIn = (lowerBound + upperBound ) / 2;


if(a[curIn]==searchKey)
return curIn; //
else if(lowerBound > upperBound)
return nElems; //
else //
{
if(a[curIn] < searchKey) //
return recFind(searchKey, curIn+1, upperBound);
else //
return recFind(searchKey, lowerBound, curIn-1);
}
}
( main()) find()
, ; -
upperBound lowerBound.
find() ,
main()
. find() lowerBound upperBound
(0 nElems-1), recFind().
find() :
public int find(long searchKey)
{
return recFind(searchKey, 0, nElems-1);
}
binarySearch.java 6.3.

6.3. binarySearch.java
// binarySearch.java
//
// : C>java BinarySearchApp
////////////////////////////////////////////////////////////////
class ordArray
{
private long[] a; // a
private int nElems; // number of data items
259

//-----------------------------------------------------------
public ordArray(int max) //
{
a = new long[max]; //
nElems = 0;
}
//-----------------------------------------------------------
public int size()
{ return nElems; }
//-----------------------------------------------------------
public int find(long searchKey)
{
return recFind(searchKey, 0, nElems-1);
}
//-----------------------------------------------------------
private int recFind(long searchKey, int lowerBound,
int upperBound)
{
int curIn;

curIn = (lowerBound + upperBound ) / 2;


if(a[curIn]==searchKey)
return curIn; //
else if(lowerBound > upperBound)
return nElems; //
else //
{
if(a[curIn] < searchKey) //
return recFind(searchKey, curIn+1, upperBound);
else //
return recFind(searchKey, lowerBound, curIn-1);
}
}
//-----------------------------------------------------------
public void insert(long value) //
{
int j;
for(j=0; j<nElems; j++) //
if(a[j] > value) // ( )
break;
for(int k=nElems; k>j; k--) //
a[k] = a[k-1]; //
a[j] = value; //
nElems++; //
}
//-----------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //

260 6.

6.3 ()
System.out.print(a[j] + " "); //
System.out.println("");
}
//-----------------------------------------------------------
} // ordArray
////////////////////////////////////////////////////////////////
class BinarySearchApp
{
public static void main(String[] args)
{
int maxSize = 100; //
ordArray arr; //
arr = new ordArray(maxSize); //

arr.insert(72); //
arr.insert(90);
arr.insert(45);
arr.insert(126);
arr.insert(54);
arr.insert(99);
arr.insert(144);
arr.insert(27);
arr.insert(135);
arr.insert(81);
arr.insert(18);
arr.insert(108);
arr.insert(9);
arr.insert(117);
arr.insert(63);
arr.insert(36);

arr.display(); //

int searchKey = 27; //


if( arr.find(searchKey) != arr.size() )
System.out.println("Found " + searchKey);
else
System.out.println("Cant find " + searchKey);
}
} // BinarySearchApp
////////////////////////////////////////////////////////////////
main() 16 . insert()
, .
, find() 27.
:
9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144
Found 27
261

binarySearch.java 16 . .6.9
, recFind()
.
27, 2 (
). -
recFind(); , find()
.
, -
: O(logN). ,
.

. 6.9. binarySearch()
262 6.



. ` , -
. :
. ,
, .
-
, , 2,
. ,
, ,
( ). -
, (
). , -
, (
).


,
(.6.10).

. 6.10.

, ,
. A.
A C.
,
.
, -
, 64 .
, . , -
, ,
.
263

Towers Workshop

Towers
Workshop

. -
,
. .6.11 ,
.

. 6.11. Towers Workshop

Towers Workshop :
,
.
Step ,
. -
.
Run ;
.
, ( 1 10)
New. (
.)
A
. -
, Step Run;
New. , -
,
.

(, 3 4). .
, .
264 6.


A . (
, -
.)
, .
, ,
. , ,
B
(.6.12).

. 6.12. B

.
,
: -
, .
. -
,
, .

.


-
. ,
(
S
) (
D
). -
(I). S n .
:
1. , n1 , S I.
2. ( ) S D.
3. I D.
A

, B

, -
C. .6.13 .
, 1, 2 3, -
B. 4 C,
B C.
265

. 6.13.

, ,
1, 2 3 B ,
.
, , .
,
A
B

-
, . ,
A
C, 3 A B.
C B.
A

C

? , -
(1), A B. :
,
. (2) A C;
1.
266 6.

towers.java
towers.java
. ; -
, . ,
, ,
.
. main()
doTowers().
, . , -
6.4, ,
.

6.4. towers.java
// towers.java
// " "
// : C>java TowersApp
////////////////////////////////////////////////////////////////
class TowersApp
{
static int nDisks = 3;

public static void main(String[] args)


{
doTowers(nDisks, 'A', 'B', 'C');
}
//-----------------------------------------------------------
public static void doTowers(int topN,
char from, char inter, char to)
{
if(topN==1)
System.out.println("Disk 1 from " + from + " to "+ to);
else
{
doTowers(topN-1, from, to, inter); // from-->inter
System.out.println("Disk " + topN +
" from " + from + " to "+ to);
doTowers(topN-1, inter, from, to); // inter-->to
}
}
//----------------------------------------------------------
} // TowersApp
////////////////////////////////////////////////////////////////
, A C.
:
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
267

Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
doTowers() , -
(from), (inter) (to) .
. .
,
, :
(Base case) -
(Move bottom disk) :
Enter (3 disks): s=A, i=B, d=C
Enter (2 disks): s=A, i=C, d=B
Enter (1 disk): s=A, i=B, d=C
Base case: move disk 1 from A to C
Return (1 disk)
Move bottom disk 2 from A to B
Enter (1 disk): s=C, i=A, d=B
Base case: move disk 1 from C to B
Return (1 disk)
Return (2 disks)
Move bottom disk 3 from A to C
Enter (2 disks): s=B, i=A, d=C
Enter (1 disk): s=B, i=C, d=A
Base case: move disk 1 from B to A
Return (1 disk)
Move bottom disk 2 from B to C
Enter (1 disk): s=A, i=B, d=C
Base case: move disk 1 from A to C
Return (1 disk)
Return (2 disks)
Return (3 disks)
doTower(),
, . ,
( ) .


.
, 3,
. -
, -
O(N2), O(NlogN).
.

2.9 ( 2) , . -
, N ( ) 10000,
268 6.

N2 100000000, NlogN 40000.


40 ,
28 . ,
. -
, .
, -
,
. ,
,
.


-
.
A B C, A B,
.
, , .
,
( ). ,
A
4-
, B 6. C,
10 (.6.14).

. 6.14. : ;


A B C. 6.3 ,
.
. A.
8
B
, -
; A C.
269

6.3.

1 23 7 7 B C
2 23 14 14 A C
3 23 39 23 A C
4 39 47 39 B C
5 55 47 47 A C
6 55 81 55 B C
7 62 81 62 B C
8 74 81 74 B C
9 81 A C

10 95 A C

6.5
Java
, -
.6.14 .6.3.
; .

6.5. merge.java
// merge.java
//
// : C>java MergeApp
////////////////////////////////////////////////////////////////
class MergeApp
{
public static void main(String[] args)
{
int[] arrayA = {23, 47, 81, 95};
int[] arrayB = {7, 14, 39, 55, 62, 74};
int[] arrayC = new int[10];

merge(arrayA, 4, arrayB, 6, arrayC);


display(arrayC, 10);
}
//-----------------------------------------------------------
// A B C
public static void merge( int[] arrayA, int sizeA,
int[] arrayB, int sizeB,
int[] arrayC )
{
int aDex=0, bDex=0, cDex=0;
while(aDex < sizeA && bDex < sizeB) //
if( arrayA[aDex] < arrayB[bDex] )
arrayC[cDex++] = arrayA[aDex++];

270 6.

6.5 ()
else
arrayC[cDex++] = arrayB[bDex++];
while(aDex < sizeA) // arrayB ,
arrayC[cDex++] = arrayA[aDex++]; // arrayA
while(bDex < sizeB) // arrayA ,
arrayC[cDex++] = arrayB[bDex++]; // arrayB
}
//-----------------------------------------------------------
//
public static void display(int[] theArray, int size)
{
for(int j=0; j<size; j++)
System.out.print(theArray[j] + " ");
System.out.println("");
}
//-----------------------------------------------------------
} // MergeApp
////////////////////////////////////////////////////////////////
main() arrayA, arrayB arrayC.
merge(), arrayA arrayB arrayC,
arrayC. :
7 14 23 39 47 55 62 74 81 95
merge() while.
arrayA arrayB, arrayC.
, arrayB
, arrayA (
, arrayA 81 95).
arrayA arrayC.
,
arrayA, arrayB ; arrayC.


, ,
, merge()
.
? , , , :
, ,
.
8-
.. ,
. ; ,
.
,
,
. mergeSort() -
271

,
.
mergeSort() -
, ,
. 2- -
4- .
, .
,
2, . 6.15.
0 1 2 3 4 5 6 7

64 21 33 70 12 85 44 3

21 64

33 70

21 33 64 70

12 85

3 44

3 12 44 85

3 12 21 33 44 64 70 85

. 6.15.
272 6.

0-0 1-1 -
0-1. , 0-0 1-1 ;
, .
2-2 3-3 2-3, 0-1 2-3
0-3.

. 6.16. 2
273

4-4 5-5 4-5,


6-6 7-7 6-7, 4-5 6-7 4-7. ,
0-3 4-7 0-7,
.
2,
. , .6.16 ,
12 .
, .
0-0 1-1 0-1
. 0-1
2-2, 0-2. -
3-5, . ,
.
: -
, merge.java. -
.
, ?
, .
,
.
.

MergeSort Workshop
, -
. MergeSort

Workshop

. -
Step . .6.17
, .

. 6.17. MergeSort Workshop


274 6.

Lower Upper , -
, Mid . -
,
mergeSort().
, mergeSort() ( ).
.
, -
(, Entering mergeSort: 0-5).
mergeSort() -
.
, Merged 0-0 and 1-1.
, ,
. -
() :
.
, ,
3-4, 3-5, 0-5
.6.16.
.
Run .
Step; ,
,
Run.
Workshop, New

. Size -
(12 100 ).
, -
100 , .
, ,
.

mergeSort.java
mergeSort.java . -
, .
:
private void recMergeSort(long[] workSpace, int lowerBound,
int upperBound)
{
if(lowerBound == upperBound) // ,
return; // .
else
{ //
int mid = (lowerBound+upperBound) / 2;
275

//
recMergeSort(workSpace, lowerBound, mid);
//
recMergeSort(workSpace, mid+1, upperBound);
//
merge(workSpace, lowerBound, mid+1, upperBound);
}
}
, ,
. , -
recMergeSort() (
) , , merge() .
,
(lowerBound==upperBound); .
mergeSort.java mergeSort().
workSpace[] recMergeSort()
. merge-
Sort(), recMergeSort()
(, ). merge()
merge.java ( 6.5)
: . merge() mergeSort.java
: theArray DArray.
merge() ,
, -
. .
6.6 mergeSort.java, -
2 DArray
mergeSort() recMergeSort(). main() ,
12, ,
mergeSort() .

6.6. mergeSoft.java
// mergeSort.java
//
// : C>java MergeSortApp
////////////////////////////////////////////////////////////////
class DArray
{
private long[] theArray; // theArray
private int nElems; //
//-----------------------------------------------------------
public DArray(int max) //
{
theArray = new long[max]; //
nElems = 0;
}

276 6.

6.6 ()
//-----------------------------------------------------------
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
//-----------------------------------------------------------
public void display() //
{
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//-----------------------------------------------------------
public void mergeSort() // main()
{ //
long[] workSpace = new long[nElems];
recMergeSort(workSpace, 0, nElems-1);
}
//-----------------------------------------------------------
private void recMergeSort(long[] workSpace, int lowerBound,
int upperBound)
{
if(lowerBound == upperBound) // ,
return; // .
else
{ //
int mid = (lowerBound+upperBound) / 2;
//
recMergeSort(workSpace, lowerBound, mid);
//
recMergeSort(workSpace, mid+1, upperBound);
//
merge(workSpace, lowerBound, mid+1, upperBound);
}
}
//-----------------------------------------------------------
private void merge(long[] workSpace, int lowPtr,
int highPtr, int upperBound)
{
int j = 0; //
int lowerBound = lowPtr;
int mid = highPtr-1;
int n = upperBound-lowerBound+1; //

while(lowPtr <= mid && highPtr <= upperBound)


if( theArray[lowPtr] < theArray[highPtr] )
workSpace[j++] = theArray[lowPtr++];
else
277

workSpace[j++] = theArray[highPtr++];

while(lowPtr <= mid)


workSpace[j++] = theArray[lowPtr++];

while(highPtr <= upperBound)


workSpace[j++] = theArray[highPtr++];

for(j=0; j<n; j++)


theArray[lowerBound+j] = workSpace[j];
}
//-----------------------------------------------------------
} // DArray
////////////////////////////////////////////////////////////////
class MergeSortApp
{
public static void main(String[] args)
{
int maxSize = 100; //
DArray arr; //
arr = new DArray(maxSize); //

arr.insert(64); //
arr.insert(21);
arr.insert(33);
arr.insert(70);
arr.insert(12);
arr.insert(85);
arr.insert(44);
arr.insert(3);
arr.insert(99);
arr.insert(0);
arr.insert(108);
arr.insert(36);

arr.display(); //

arr.mergeSort(); //

arr.display(); //
}
} // MergeSortApp
////////////////////////////////////////////////////////////////
, :
64 21 33 70 12 85 44 3 99 0 108 36
0 3 12 21 33 36 44 64 70 85 99 108
recMergeSort() -
, -
. ,
278 6.

{64, 21, 33, 70} (


.6.15).
Entering 0-3
Will sort low half of 0-3
Entering 0-1
Will sort low half of 0-1
Entering 0-0
Base-Case Return 0-0
Will sort high half of 0-1
Entering 1-1
Base-Case Return 1-1
Will merge halves into 0-1
Return 0-1 theArray=21 64 33 70
Will sort high half of 0-3
Entering 2-3
Will sort low half of 2-3
Entering 2-2
Base-Case Return 2-2
Will sort high half of 2-3
Entering 3-3
Base-Case Return 3-3
Will merge halves into 2-3
Return 2-3 theArray=21 64 33 70
Will merge halves into 0-3
Return 0-3 theArray=21 33 64 70
MergeSort
Workshop . ;
recMergeSort() . 6.15 -
.


, O(N logN).
? ,

. ,
, -
.


.6.15. ,
.
.6.15 ( ) ,
8 24 . log28
3, 8 log28 24. , 8
N log2N.
279

:
, 8 -
. -
. 2- ;
4-; 8-.
8 ; 38=24 .
.6.15, , , -
( 1, 2 3) 8 ,
2 .

. 6.4
.

6.4. N, 2
N log2N - -
- ()

(Nlog2N)
2 1 2 4 1 (1)
4 2 8 16 5 (4)
8 3 24 48 17 (12)
16 4 64 128 49 (32)
32 5 160 320 129 (80)
64 6 384 768 321 (192)
128 7 896 1792 769 (448)

,
. , (
). . 6.4 -
; .
N 2,
,
2. 12 -
88, 100 1344.



. ? ,
2, -
,
, .
, .6.18,
, 4 .
280 6.

. 6.18.


. -
, .
, -
. .6.15, ,
.
.6.5.

6.5.

1 2 3 4 5 6 7
(N) 2 2 4 2 2 4 8 24
(N1) 1 1 3 1 1 3 7 17
(N/2) 1 1 2 1 1 2 4 12


.
17.
-
. , 12. -
281

.6.4 .
,
- -
.


, .
, triangle() factorial() -
. ,
(, )
.

, .
.
.


.
. , -
(
) , -
. .
, .


, -
. triangle()
?
int triangle(int n)
{
if(n==1)
return 1;
else
return( n + triangle(n-1) );
}
,
case switch. ( C++
goto, Java goto
.)
switch step. step()
case. step() -
.
282 6.

triangle() . -
, ,
: n 1 n
. triangle() ,
, , -
. , -
. :
.
, .

, -
.
stackTriangle.java : Params, StackX StackTrian-
gleApp. Params n;
. StackX
, Params. StackTriangleApp
: main(), recTriangle(), step() getInt()
.
main() , recTriangle()
n, .
recTriangle() StackX codePart
1. while step().
, step() true case 6 (
). , step()
switch, case
triangle(). stackTriangle.java -
6.7.
6.7. stackTriangle.java
// stackTriangle.java
//
// : C>java StackTriangleApp
import java.io.*; // /
////////////////////////////////////////////////////////////////
class Params // ,
{
public int n;
public int returnAddress;

public Params(int nn, int ra)


{
n=nn;
returnAddress=ra;
}
} // Params
////////////////////////////////////////////////////////////////
283

class StackX
{
private int maxSize; // StackX
private Params[] stackArray;
private int top; //
//--------------------------------------------------------------
public StackX(int s) //
{
maxSize = s; //
stackArray = new Params[maxSize]; //
top = -1; //
}
//--------------------------------------------------------------
public void push(Params p) //
{
stackArray[++top] = p; // top,
}
//--------------------------------------------------------------
public Params pop() //
{
return stackArray[top--]; // , top
}
//--------------------------------------------------------------
public Params peek() //
{
return stackArray[top];
}
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class StackTriangleApp
{
static int theNumber;
static int theAnswer;
static StackX theStack;
static int codePart;
static Params theseParams;
//-------------------------------------------------------------
public static void main(String[] args) throws IOException
{
System.out.print("Enter a number: ");
theNumber = getInt();
recTriangle();
System.out.println("Triangle="+theAnswer);
}
//-------------------------------------------------------------
public static void recTriangle()
{
theStack = new StackX(10000);

284 6.

6.6 ()
codePart = 1;
while( step() == false) // , step() true
; //
}
//-------------------------------------------------------------
public static boolean step()
{
switch(codePart)
{
case 1: //
theseParams = new Params(theNumber, 6);
theStack.push(theseParams);
codePart = 2;
break;
case 2: //
theseParams = theStack.peek();
if(theseParams.n == 1) //
{
theAnswer = 1;
codePart = 5; //
}
else
codePart = 3; //
break;
case 3: //
Params newParams = new Params(theseParams.n - 1, 4);
theStack.push(newParams);
codePart = 2; //
break;
case 4: //
theseParams = theStack.peek();
theAnswer = theAnswer + theseParams.n;
codePart = 5;
break;
case 5: //
theseParams = theStack.peek();
codePart = theseParams.returnAddress; // (4 6)
theStack.pop();
break;
case 6: //
return true;
}
return false;
}
//-------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
285

String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//--------------------------------------------------------------
} // StackTriangleApp
////////////////////////////////////////////////////////////////
, -
triangle.java (. 6.1). :
Enter a number: 100
Triangle=5050
.6.19 , case
.
, ,
Java, . sim-
Meth(). simMeth() (case 1) , -
, 6 simMeth() (case 2).
(case 2) simMeth() , 1.
. 1, -
, simMeth() (case 5).
(case 3).
n-1 4 -
(case 2).
simMeth() n
, ,
(case 5). Params;
.
, , 6, -
case 6. true,
while recTriangle() .
: simMeth()
, , ; -
, Java.
case , -
,
:
Enter a number: 4
case 1. theAnswer=0 Stack:
case 2. theAnswer=0 Stack: (4, 6)
case 3. theAnswer=0 Stack: (4, 6)
case 2. theAnswer=0 Stack: (4, 6) (3, 4)
286 6.

case 3. theAnswer=0 Stack: (4, 6) (3, 4)


case 2. theAnswer=0 Stack: (4, 6) (3, 4) (2, 4)
case 3. theAnswer=0 Stack: (4, 6) (3, 4) (2, 4)
case 2. theAnswer=0 Stack: (4, 6) (3, 4) (2, 4) (1, 4)
case 5. theAnswer=1 Stack: (4, 6) (3, 4) (2, 4) (1, 4)
case 4. theAnswer=1 Stack: (4, 6) (3, 4) (2, 4)
case 5. theAnswer=3 Stack: (4, 6) (3, 4) (2, 4)
case 4. theAnswer=3 Stack: (4, 6) (3, 4)
case 5. theAnswer=6 Stack: (4, 6) (3, 4)
case 4. theAnswer=6 Stack: (4, 6)
case 5. theAnswer=10 Stack: (4, 6)
case 6. theAnswer=10 Stack:
Triangle=10

. 6.19. case step


287

case , .
( Params n
). simMeth() (case 2);
(case 5). theAnswer
.

?
stackTriangle.java ( 6.7) -
, , -
, . ,
.
, ,
switch .
, -
. 6.8
triangle().

6.8. stackTriangle2.java
// stackTriangle2.java
// ( )
// : C>java StackTriangle2App
import java.io.*; // /
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize; //
private int[] stackArray;
private int top; //
//--------------------------------------------------------------
public StackX(int s) //
{
maxSize = s;
stackArray = new int[maxSize];
top = -1;
}
//--------------------------------------------------------------
public void push(int p) //
{ stackArray[++top] = p; }
//--------------------------------------------------------------
public int pop() //
{ return stackArray[top--]; }
//--------------------------------------------------------------
public int peek() //
{ return stackArray[top]; }
//--------------------------------------------------------------

288 6.

6.6 ()
public boolean isEmpty() // true,
{ return (top == -1); }
//--------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class StackTriangle2App
{
static int theNumber;
static int theAnswer;
static StackX theStack;

public static void main(String[] args) throws IOException


{
System.out.print("Enter a number: ");
theNumber = getInt();
stackTriangle();
System.out.println("Triangle="+theAnswer);
}
//-------------------------------------------------------------
public static void stackTriangle()
{
theStack = new StackX(10000); //

theAnswer = 0; //

while(theNumber > 0) // 1
{
theStack.push(theNumber); //
--theNumber; //
}
while( !theStack.isEmpty() ) //
{
int newN = theStack.pop(); //
theAnswer += newN; //
}
}
//-------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
289

return Integer.parseInt(s);
}
//-------------------------------------------------------------
} // StackTriangle2App
while stackTriangle() step()
stackTriangle.java. ,
, .
.
, ( , ,
) ,
.


, -
. ,
. :
, .
,
.



. x^y; ^ , x
y. , -
? , x y . -
, x 2, y 8 (28),
2222222 2. y
. ?
,
2 , 2. -
28. 2 8 .
22=4. , .
: 4. , 4 4 = 16.
( 4 2 2). -
2, 16,
1616=256 ( -
16 ).
, 28
. O(N) O(log N).
,
? xy = (x2)y/2.
290 6.

28 = (22)8/2 28 = (22)4 ,

.
,
(22)4 . , -
? 22 .
, 22 = a. 28 (22)4, a4.
a4 (a2)2, 28 = (a2)2.
a2 (, a2 = c); (c)2
(c2)1, -
28.
, c c.
(
power()) . x y -
xy. , x y
.
xx y/2. , x = 2 y = 8
:
x=2, y=8
x=4, y=4
x=16, y=2
x=256, y=1
Returning 256, x=256, y=1
Returning 256, x=16, y=2
Returning 256, x=4, y=4
Returning 256, x=2, y=8
y 1, . -
256 .
y
. .
y : ,
y 2 .
, y ,
x. 318 -
:
x=3, y=18
x=9, y=9
x=81, y=4
x=6561, y=2
x=43046721, y=1
Returning 43046721, x=43046721, y=1
Returning 43046721, x=6561, y=2
Returning 43046721, x=81, y=4
Returning 387420489, x=9, y=9 // y , x
Returning 387420489, x=3, y=18
291


1 . -

. -
.
, 20 ,
11, 8, 7, 6 5 . -
. , ,
8, 7 5 20. -
, .
:
1. -
, .
2. .
;
.
3. . ,
, -
,
.
4. , -
.
5. .., -
. ,
.
11. -
9 (2011). 8.
1 (98). 7; 1. 6, 5
. , , 8
9. 7 2 (97).
:
Items: 11, 8, 7, 6, 5
==========================================
11 // = 20, 11
11, 8 // = 9, 8
11, 8, 7 // = 1, 7
11, 8, 6 // = 1, 6
11, 8, 5 // = 1, 5 .
11, 7 // = 9, 7
11, 7, 6 // = 2, 6
11, 7, 5 // = 2, 5 .
11, 6 // = 9, 6

1
. . .
292 6.

11, 6, 5 // = 3, 5 .
11, 5 // = 9, 5 .
8, // = 20, 8
8, 7 // = 12, 7
8, 7, 6 // = 5, 6
8, 7, 5 // = 5, 5 . !
, ,
, -
.


,
. ,
A, B, C, D E.
.
, -
, -
. ,
. 10 :
ABC, ABD, ABE, ACD, ACE, ADE, BCD, BCE, BDE, CDE
? ,
. : A
. 3-
5 (5, 3). ,
n, k. -

(n, k) = (n 1, k 1) + (n 1, k).
3- 5 :
(5, 3) = (4, 2) + (4, 3).
.
5, 4: -
2- 4,
3- 4.
6 2- 4.
(4, 2) ( )
BC, BD, BE, CD, CE, DE
A; 3-
, A:
ABC, ABD, ABE, ACD, ACE, ADE
293

3- 4- . (4,
3) ( )
BCD, BCE, BDE, CDE
4 6 -
, 10 (5, 3).

4. , (4, 2) (3, 1) + (3, 2). , -
.
(5, 3),
(4, 3) (4, 2) ..; .
.6.20 , (5, 3).

5, 3

4, 2 4, 3

B B

3, 1 3, 2 3, 2 3, 3
AB

C
C

2, 0 2, 1 2, 1 2, 2 2, 1 2, 2 2, 2 2, 3
BCD
ACD
ABD

1, 1 1, 0 1, 0 1, 1 1, 0 1, 1 1, 1 1, 2 1, 0 1, 1 1, 1 1, 2 1, 1 1, 2 1, 2 1, 3
ABE

ACE

ADE

BCE

BDE

CDE

. 6.20. 3 5

, : ,
0, ,
. (1, 1) ,
. -
; .
:
A, B ..
5 , 5 .
-
. ,
, -
. , ,
.
294 6.

,
;

,
.

.
-
.
.
-

, .
-
(, ). ,
4 10, 4 + 3 + 2 + 1 = 10.

. , 4 4 3 2 1 = 24.
, -
, .
( n )
,
n1 .
; ,
, -
.

.
-
, , ,
, , -
.
,
.
1- -
2- ,
4- .., .
O(N logN).
295

, -
.
, , -
.
( , -
.)

.
, ,
.
.
.

.
.
1. , 10 triangle.java ( 6.1).
triangle() (
) ?
2. , 1?
a) triangle().
b) TriangleApp.
c) getString().
d) .
3. , 10 1. -
n, triangle() , 1?
4. , 1. n,
triangle() main()?
5. triangle() (/).
6. anagram.java ( 6.2)
doAnagram() led.
, ?
7. orderedArray.
java ( 2.4) binarySearch.java ( 6.3).
?
a) .
b)
, -
,
.
296 6.

c) , ,
.
d) -
, .
8.
recFind() binarySearch.java ( 6.3)?
a) recFind().
b) recFind().
c) recFind().
d) recFind() main().
9. binarySearch.java _________.
10. recFind()?
11. towers.
java ( 6.4)?
12. towers.java :
a) ;
b) ;
c) ;
d)
.
13. merge() -
merge.java ( 6.5)?
a) .
b)
.
c) .
d) ,
.
14. :
a) ;
b) ;
c)
, ;
d) .
15. , ___________.
297

.
.
1. triangle.java ( 6.1)
(if(n==1), return 1; else). , .
2. Towers Workshop ,
.
3. main() mergeSort.java ( 6.6),
. -

3, .


,

.
6.1. , ,
. -
, mult(),
xy x y . x y -
, . main(),
.
?
6.2. 8, , , -
() .
,
, , 4, 8, 16 .. , 16
:
--------X-------
----X-------X---
--X---X---X---X-
-X-X-X-X-X-X-X-X
XXXXXXXXXXXXXXXX
(, - ,
.) -
makeBranches() left right,
.
left 0, right ( )
. X ,
: . -
298 6.

, . X
, ,
display(). main(), , -
makeBranches() display(). main()
(32, 64 ..) ,
.
(5 ) ?
6.3. (.
). power()
main() .
6.4. ,
. .
: knapsack()
, .
6.5. (n -
k ). showTeams() main(),

showTeam(), .
7

, 3, ,
, -
. 6, , .
,
; -
.
:
. : -
O(N(logN)2),
O(NlogN). ,
.
, , -
.

.
. -
, , -
.


. -
,
1959. , -
, .
-
, ( ).
,
O(NlogN), -
. O(N2) ,
.
: .
-
. ( , -
,
.) (
300 7.

) -
,
(, ) , -
.

:

, ,
3. ,

( ),
. , -
, . ,
, ,

.
.
, , -
. -
, (
) . -
- N .
N ,
N/2 . N/2 N ,
N2/2. , -
O(N2).
, -
.

N-
, -
.
, . .
-
h. .7.1
10- 4. 0, 4 8.
0, 4 8,
1, 5 9. ,
4-, , -
4- , .
.7.2 ( ).
301

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

. 7.1. 4- 0, 4 8

7 10 1 9 2 5 8 6 4 3

0 1 2 3 4 5 6 7 8 9

2 10 1 9 4 5 8 6 7 3

0 1 2 3 4 5 6 7 8 9

2 3 1 9 4 5 8 6 7 10

0 1 2 3 4 5 6 7 8 9

2 3 1 9 4 5 8 6 7 10

0 1 2 3 4 5 6 7 8 9

2 3 1 6 4 5 8 9 7 10

0 1 2 3 4 5 6 7 8 9

. 7.2. 4-
302 7.

4-
: (0,4,8), (1,5,9), (2,6) (3,7),
. ,
.
: 4-
, -
.
.

, .
, 3,
. -
- , -
O(N). , 4-
1- .
4- 1- ,
4-.


10
4 . -
, -
1.
, 1000 364-,
121-, 40-, 13-, 4- , , 1--
. , (
364, 121, 40, 13, 4, 1), .
, (. -
), . , 1,

h = 3 h + 1.
( h 1).
. 7.1.
-
; . ,
.

. h 1,
h =h3+1 1, 4, 13, 40, 121, 364 ..
, .
1000 (1093) -
;
303

(364). -

, :
h = (h1)/3.
. 7.1.
364, 121, 40, 13, 4, 1.
, 364, n- . 1--
.

7.1.
h 3*h+1 (h1)/3
1 4
4 13 1
13 40 4
40 121 13
121 364 40
364 1093 121
1093 3280 364

Shellsort Workshop

Shellsort

Workshop
, -
. .7.3 ,
4-, 1-.

. 7.3. Shellsort Workshop


304 7.

,
. 4-
(0,4,8), (1,5,9), (2,6) (3,7). -
,
..
, -
. ,
(0,4), (1,5), (2,6), (3,7), (0,4,8), (1,5,9).
4-
(0,4), (0,4,8), (1,5), (1,5,9), (2,6), (3,7),
.
10 ;
.
, 100 .
100 , -
. ( 3, New
, ,
.) .7.4 ,
, 40- . .7.5
, 13-.
h .

. 7.4. 40-

,
? h
, . -
h ,
305

,
.
.

. 7.5. 13-

, ( -
h) ( h).
, , 40-, 40-
13-. ,
.

Java
Java
. 1 -
h, -
.
shellSort() ArraySh 2, .
shellSort.java 7.1.

7.1. shellSort.java
// shellSort.java
//
// : C>java ShellSortApp
//--------------------------------------------------------------
class ArraySh

306 7.

7.1 ()
{
private long[] theArray; //
private int nElems; //
//--------------------------------------------------------------
public ArraySh(int max) //
{
theArray = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
System.out.print("A=");
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void shellSort()
{
int inner, outer;
long temp;
int h = 1; // h
while(h <= nElems/3)
h = h*3 + 1; // (1, 4, 13, 40, 121, ...)

while(h>0) // h 1
{
// h-
for(outer=h; outer<nElems; outer++)
{
temp = theArray[outer];
inner = outer;
// (0, 4, 8)
while(inner > h-1 && theArray[inner-h] >= temp)
{
theArray[inner] = theArray[inner-h];
inner -= h;
}
theArray[inner] = temp;
}
h = (h-1) / 3; // h
}
}
307

//--------------------------------------------------------------
} // ArraySh
////////////////////////////////////////////////////////////////
class ShellSortApp
{
public static void main(String[] args)
{
int maxSize = 10; //
ArraySh arr;
arr = new ArraySh(maxSize); //

for(int j=0; j<maxSize; j++) //


{ //
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display(); //
arr.shellSort(); //
arr.display(); //
}
} // ShellSortApp
main() ArraySh 10 ,
, ,
. :
A=20 89 6 42 55 59 41 69 75 66
A=6 20 41 42 55 59 66 69 75 89
maxSize , ;
10000 .
,
. ,
10-
Workshop
-
shellSort().


, . -
-
h=h3+1, -
.
, 1,
.
-
N/2, 2 . ,
N=100 50, 25, 12, 6, 3, 1.
, -
; N
2. .
308 7.

,
O(N2) ,
.
2,2 2.
N=100 45, 20, 9, 4, 1. -
2,
O(N2). ,
, ,
1 N.
,
.
( ; . -
):
if(h < 5)
h = 1;
else
h = (5*h-1) / 11;
,
, ,
1. ,
. -
N/2 , -
.
, -
, ( , ) .
, -
, .



, .
, , O (N3/2)
O(N7/6).
7.2 O-
, -
.
N. Nx/y y N,
x. , N=100 N3/2 -
1003; 1000. , (logN)2
N, . -
log2N, log2N ( N 2).

(, N3/2).
309

7.2.
O() 10 100 1000 10000

N2 100 10000 1000000 100000000
.
N3/2 32 1000 32000 1000000
N*(logN)2 10 400 9000 160000
5/4
N 18 316 5600 100000
7/6
N 14 215 3200 46000
N*logN 10 200 3000 40000
.

, , -
. , ,
.
,
,
.
, -
. , -
: 15 ,
. , , :
3,5 , .

Partition Workshop
Partition Workshop . .7.6
12 , .7.7 -
.
,
. ,
, ,
( ) . ( ,
, , -
. .)
partition
() .
, ,
.
310 7.

. 7.6.

. 7.7.

,
Partition Workshop 100 Run.
leftScan rightScan , .
, .
(,
3,5). Partition

Work-

shop (
) New Size,
.
311

;
. , .
,
.
, . , -

. ,
.

partition.java
? . 7.2
partition.java, partitionIt() -
.

7.2. partition.java
// partition.java
//
// : C>java PartitionApp
////////////////////////////////////////////////////////////////
class ArrayPar
{
private long[] theArray; //
private int nElems; //
//--------------------------------------------------------------
public ArrayPar(int max) //
{
theArray = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public int size() //
{ return nElems; }
//--------------------------------------------------------------
public void display() //
{
System.out.print("A=");
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------

312 7.

7.1 ()
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left - 1; //
int rightPtr = right + 1; //
while(true)
{
while(leftPtr < right && //
theArray[++leftPtr] < pivot)
; // ( )

while(rightPtr > left && //


theArray[--rightPtr] > pivot)
; // ( )
if(leftPtr >= rightPtr) // ,
break; //
else //
swap(leftPtr, rightPtr); //
}
return leftPtr; //
}
//--------------------------------------------------------------
public void swap(int dex1, int dex2) //
{
long temp;
temp = theArray[dex1]; // A temp
theArray[dex1] = theArray[dex2]; // B A
theArray[dex2] = temp; // temp B
}
//--------------------------------------------------------------
} // ArrayPar
////////////////////////////////////////////////////////////////
class PartitionApp
{
public static void main(String[] args)
{
int maxSize = 16; //
ArrayPar arr; //
arr = new ArrayPar(maxSize); //

for(int j=0; j<maxSize; j++) //


{ //
long n = (int)(java.lang.Math.random()*199);
arr.insert(n);
}
arr.display(); //

long pivot = 99; //


System.out.print("Pivot is " + pivot);
int size = arr.size();
313

//
int partDex = arr.partitionIt(0, size-1, pivot);

System.out.println(", Partition is at index " + partDex);


arr.display(); //
}
main() ArrayPar 16 long.
99. ArrayPar 16 -
, , partitionIt(),
. :
A=149 192 47 152 159 195 61 66 17 167 118 64 27 80 30 105
Pivot is 99, partition is at index 8
A=30 80 47 27 64 17 61 66 195 167 118 159 152 192 149 105
, : -
99, .
, -
, ;
. ,
.



. ( , ,
, C++.) leftPtr
, rightPtr .
: leftPtr rightPtr partition.java
leftScan rightScan Partition Workshop.
, leftPtr ,
rightPtr ,
.


leftPtr , ,
, .
, , .
, rightPtr ,
, ,
. while,
leftPtr rightPtr. -
.
:
while( theArray[++leftPtr] < pivot ) //
; // ( )
314 7.

while( theArray[--rightPtr] > pivot ) //


; // ( )
swap(leftPtr, rightPtr); //
while ,
pivot; -
, pivot. leftPtr,
rightPtr , ;
.
. -
, ,
. while (. partitionIt()
7.2). , , -
while .
, Partition
Workshop
100 . , , -
.
, .
; -
. ,
.


, ,
, , -
, while
. , ,
.
, , leftPtr

.
rightPtr, .
, while -
: leftPtr<right
rightPtr>left . 7.2.
, , , -
-
.
.


while .
, ++
. ,
315

while(leftPtr < right && theArray[++leftPtr] < pivot)


; // ( )
:
while(leftPtr < right && theArray[leftPtr] < pivot)
++leftPtr;
, while. -
left right
left-1 right+1.

. -
, while
.
.


partitionIt().
partitionIt() , -
, .
,
. < >,
while.
, <= >=,
, leftPtr rightPtr
.
, , , -
, -
. , partitionIt()
, > < ,
.


O(N).

Partition
Workshop

: -

, .
, .
, ,
,
. , -
N.
, N+1 N+2
.
, N ,
316 7.

,
.
(
).
.
, -
, ,
N/2 . ( , Partition Workshop
,
, , N/2.)
N/2
, ,
. , -
( , ).
( ) , -
, -
, ( ) .

.
,
N. ,
O(N). Workshop

, , 12 -
14 , 100
25 102 .


, -
, :
O(N*logN). (
, ;
.)
... 1962 .
, ,
. , -
,
. ,
,
.
.
317

, , , -
, :

Java
, -
QuickSort1 Workshop.


. -
:
public void recQuickSort(int left, int right)
{
if(right-left <= 0) // 1,
return; // .
else // 2
{
//
int partition = partitionIt(left, right);
recQuickSort(left, partition-1); //
recQuickSort(partition+1, right); //
}
}
:
1. : ( -
) ( ).
2. .
3. .

. ,
. ? -
.
recQuickSort()
( ), . -
, . ,
, , .
.
, par-
titionIt() (. ) .
(
). . -
.7.8.
318 7.

. 7.8.

recQuickSort() :
( left partition-1) ( par-
tition+1 right). : partition
. ? -
? .


partitionIt()?
:
;
.
.
, .
, -
, .
, :
, -
, , ,
. ,
- ,
, . .7.9
, , 36.
,
. ?
319

. 7.9.

, ,
. , -
. , ,
, , -
. ,

(36) (63).

. 63 ,
() , .
.7.10.

. 7.10.
320 7.

, ,
. -
,
( , ).
recQuickSort()
partitionIt(). :
public void recQuickSort(int left, int right)
{
if(right-left <= 0) // <= 1,
return; // .
else // 2
{
long pivot = theArray[right]; //
//
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition-1); //
recQuickSort(partition+1, right); //
}
}
-
partitionIt(),
. , -
. ,

. 7.3
quickSort1.java, .

7.3. quickSort1.java
// quickSort1.java
//
// : C>java QuickSort1App
////////////////////////////////////////////////////////////////
class ArrayIns
{
private long[] theArray; //
private int nElems; //
//--------------------------------------------------------------
public ArrayIns(int max) //
{
theArray = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
321

//--------------------------------------------------------------
public void display() //
{
System.out.print("A=");
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void quickSort()
{
recQuickSort(0, nElems-1);
}
//--------------------------------------------------------------
public void recQuickSort(int left, int right)
{
if(right-left <= 0) // <= 1,
return; //
else // 2
{
long pivot = theArray[right]; //
//
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition-1); //
recQuickSort(partition+1, right); //
}
}
//--------------------------------------------------------------
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left-1; // ( ++)
int rightPtr = right; // -1 (after --)
while(true)
{ //
while( theArray[++leftPtr] < pivot )
; // (nop)
//
while(rightPtr > 0 && theArray[--rightPtr] > pivot)
; // (nop)

if(leftPtr >= rightPtr) // ,


break; // .
else //
swap(leftPtr, rightPtr); // .
}
swap(leftPtr, right); //
return leftPtr; //
}
//--------------------------------------------------------------

322 7.

7.3 ()
public void swap(int dex1, int dex2) //
{
long temp;
temp = theArray[dex1]; // A temp
theArray[dex1] = theArray[dex2]; // B A
theArray[dex2] = temp; // temp B
}
//--------------------------------------------------------------
} // ArrayIns
////////////////////////////////////////////////////////////////
class QuickSort1App
{
public static void main(String[] args)
{
int maxSize = 16; //
ArrayIns arr;
arr = new ArrayIns(maxSize); //
for(int j=0; j<maxSize; j++) //
{ // .
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display(); //
arr.quickSort(); //
arr.display(); //
}
} // QuickSort1App
main() ArrayIns, 16
long, quickSort() .
:
A=69 0 70 6 38 38 24 56 44 26 73 77 30 45 97 65
A=0 6 24 26 30 38 38 44 45 56 65 69 70 73 77 97
partitionIt() :
while. -
partitionIt() partition.java -
7.2 :
leftPtr < right
leftPtr ,
, pivot. ?
, leftPtr
. , rightPtr while
. ( , .)

; .
.
323

QuickSort1 Workshop
,
QuickSort1 Workshop.


, -
100 Size, Run.
.7.11.

. 7.11. QuickSort1 Workshop 100

, ,
, ,
.

. ,
,
( ). , -
; .
( )
(, , ),
( ).
, .
324 7.


, ,
12 QuickSort1 Workshop
. ,
, -
,
, ( -
), .
.7.12 12 .
, -
,
.
.
,
.
( 5, 6, 7, 11 12) recQuickSort() ;
.
( 4 10) -
. -
: ,
. () .
, .7.12,
. . 7.3. recQuickSort() main() ,
recQuickSort() ,
. .

7.3. .7.12

1 1
2, 8 2
3, 7, 9 3
4, 10 4
5, 6, 11 5

, .
, ,
..
, .
8 , 16,
, -
.
325

0 1 2 3 4 5 6 7 8 9 10 11

90 100 20 60 80 110 120 40 10 30 50 70

30 10 20 60 40 50 70 120 80 100 90 110

30 10 20 40 50 60 70 120 80 100 90 110

30 10 20 40 50 60 70 120 80 100 90 110

10 20 30 40 50 60 70 120 80 100 90 110

5 6 7 8

10 20 30 40 50 60 70 90 80 100 110 120

10 20 30 40 50 60 70 90 80 100 110 120

10

10 20 30 40 50 60 70 80 90 100 110 120


Fig 7-2

1111 12

. 7.12.

, 12
5 :
. ,
326 7.

2 (log2N). -
.

.


QuickSort

1
Workshop
-
.
,
: leftScan rightScan , -
.
. (, ,
.)
leftScan
. , ,
. 3 9
.7.12 leftScan ,
. ,
, leftScan
. , leftScan
;
.
, leftScan rightScan -
left-1 right. ,
left 0; leftScan 1. -
rightScan ,
.
,
.
; ,
(25) 2 5.
, -
, , Array partitioned; left (76), right (88).
(88) (8), (76)?
; recQuickSort() left
right . :
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition-1); //
recQuickSort(partition+1, right); //
, partitionIt() left = 7 right = 8
7 ,
recQuickSort() (76), (88).
. recQuickSort() -
, 1, -
327

.
.7.12, () recQuickSort().

O(N2)

QuickSort
1 Workshop

100 , -
, ,
, -
, .
?
- . -
. ,
,
. ,
. -
.
, , -
.
N -
, 1 N1 . ( 3 9
.7.12.) 1 N1 ,
. -
, :
,
N1 , .
, -
QuickSort1 Workshop 12 ,
. ,
.
, O(N2).
, O(N2)
.
.
. , -
.
: QuickSort1
. ,
. -
, ( ),
.
?
328 7.


.
,
. , ,
. ,
. ,
, .
, -
.
. ,
(.7.13).

. 7.13.

, ,
. -
, -
. ,
,
.
,
: rightPtr>left
while,
. ?
,
, . .7.14.
-
,
( ),
( ). , leftPtr rightPtr
,
leftPtr>right rightPtr<left. ( , -
, , ,
.) left right
(sentinels), leftPtr rightPtr
.
329

. 7.14. ,

-
:
. left+1 right-1,
left right . , left
, -
, right ,
.
, , ,
O(N2) ,
,
.

quickSort2.java
7.4 quickSort2.java, -
. ,
medianOf3().
, partitionIt().

7.4. quickSort2.java
// quickSort2.java
//
// : C>java QuickSort2App
////////////////////////////////////////////////////////////////
class ArrayIns
{
private long[] theArray; //
private int nElems; //

330 7.

7.4 ()
//--------------------------------------------------------------
public ArrayIns(int max) //
{
theArray = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
System.out.print("A=");
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void quickSort()
{
recQuickSort(0, nElems-1);
}
//--------------------------------------------------------------
public void recQuickSort(int left, int right)
{
int size = right-left+1;
if(size <= 3) //
manualSort(left, right);
else //
{
long median = medianOf3(left, right);
int partition = partitionIt(left, right, median);
recQuickSort(left, partition-1);
recQuickSort(partition+1, right);
}
}
//--------------------------------------------------------------
public long medianOf3(int left, int right)
{
int center = (left+right)/2;
// left center
if( theArray[left] > theArray[center] )
swap(left, center);
// left right
if( theArray[left] > theArray[right] )
swap(left, right);
331

// center right
if( theArray[center] > theArray[right] )
swap(center, right);

swap(center, right-1); //
return theArray[right-1]; //
}
//--------------------------------------------------------------
public void swap(int dex1, int dex2) //
{
long temp = theArray[dex1]; // A temp
theArray[dex1] = theArray[dex2]; // B A
theArray[dex2] = temp; // temp B
}
//--------------------------------------------------------------
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left; //
int rightPtr = right - 1; //

while(true)
{
while( theArray[++leftPtr] < pivot ) //
; // ( )
while( theArray[--rightPtr] > pivot ) //
; // ( )
if(leftPtr >= rightPtr) // ,
break; //
else //
swap(leftPtr, rightPtr); //
}
swap(leftPtr, right-1); //
return leftPtr; //
}
//--------------------------------------------------------------
public void manualSort(int left, int right)
{
int size = right-left+1;
if(size <= 1)
return; //
if(size == 2)
{ // 2- left right
if( theArray[left] > theArray[right] )
swap(left, right);
return;
}
else // 3
{ // 3- left, center right
if( theArray[left] > theArray[right-1] )

332 7.

7.4 ()
swap(left, right-1); // left, center
if( theArray[left] > theArray[right] )
swap(left, right); // left, right
if( theArray[right-1] > theArray[right] )
swap(right-1, right); // center, right
}
}
//--------------------------------------------------------------
} // ArrayIns
////////////////////////////////////////////////////////////////
class QuickSort2App
{
public static void main(String[] args)
{
int maxSize = 16; //
ArrayIns arr; //
arr = new ArrayIns(maxSize); //
for(int j=0; j<maxSize; j++) //
{ //
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display(); //
arr.quickSort(); //
arr.display(); //
}
} // QuickSort2App
-
manualSort(). ( ) -
, ; 2
; 3
. recQuickSort()
,
.
main() quickSort2.java , -
quickSort1.java.

QuickSort2 Workshop
QuickSort2 Workshop
. -
QuickSort1 Workshop, ,
,
. ,
. ,
.
333

-
100 , .
1 N 1 , .
, -
QuickSort2 Workshop , QuickSort1.
;
.


,
.
3 .
.
?




. 3
10, 20 . -
,
. (. )
9, ,
, ( ) ..
quickSort3.java ( 7.5) -
, 10 .
7.5. quickSort3.java
// quickSort3.java
//
// : C>java QuickSort3App
////////////////////////////////////////////////////////////////
class ArrayIns
{
private long[] theArray; //
private int nElems; //
//--------------------------------------------------------------
public ArrayIns(int max) //
{
theArray = new long[max]; //
nElems = 0; //
}
//--------------------------------------------------------------

334 7.

7.5 ()
public void insert(long value) //
{
theArray[nElems] = value; //
nElems++; //
}
//--------------------------------------------------------------
public void display() //
{
System.out.print("A=");
for(int j=0; j<nElems; j++) //
System.out.print(theArray[j] + " "); //
System.out.println("");
}
//--------------------------------------------------------------
public void quickSort()
{
recQuickSort(0, nElems-1);
// insertionSort(0, nElems-1); //
}
//--------------------------------------------------------------
public void recQuickSort(int left, int right)
{
int size = right-left+1;
if(size < 10) //
insertionSort(left, right); //
else //
{ //
long median = medianOf3(left, right);
int partition = partitionIt(left, right, median);
recQuickSort(left, partition-1);
recQuickSort(partition+1, right);
}
}
//--------------------------------------------------------------
public long medianOf3(int left, int right)
{
int center = (left+right)/2;
// left center
if( theArray[left] > theArray[center] )
swap(left, center);
// left right
if( theArray[left] > theArray[right] )
swap(left, right);
// center right
if( theArray[center] > theArray[right] )
swap(center, right);

swap(center, right-1); //
return theArray[right-1]; //
}
335

//--------------------------------------------------------------
public void swap(int dex1, int dex2) //
{
long temp = theArray[dex1]; // A temp
theArray[dex1] = theArray[dex2]; // B A
theArray[dex2] = temp; // temp B
}
//--------------------------------------------------------------
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left; //
int rightPtr = right - 1; //
while(true)
{
while( theArray[++leftPtr] < pivot ) //
; // ( )
while( theArray[--rightPtr] > pivot ) //
; // ( )
if(leftPtr >= rightPtr) // ,
break; //
else //
swap(leftPtr, rightPtr); //
}
swap(leftPtr, right-1); //
return leftPtr; //
}
//--------------------------------------------------------------
//
public void insertionSort(int left, int right)
{
int in, out;
// out
for(out=left+1; out<=right; out++)
{
long temp = theArray[out]; //
in = out; // out
//
while(in>left && theArray[in-1] >= temp)
{
theArray[in] = theArray[in-1]; //
--in; //
}
theArray[in] = temp; //
}
}
//--------------------------------------------------------------
} // ArrayIns
////////////////////////////////////////////////////////////////

336 7.

7.5 ()
class QuickSort3App
{
public static void main(String[] args)
{
int maxSize = 16; //
ArrayIns arr; //
arr = new ArrayIns(maxSize); //

for(int j=0; j<maxSize; j++) //


{ //
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display(); //
arr.quickSort(); //
arr.display(); //
}

,
(
quickSort2.java).
,
,
. , -
.


:
, . -
quickSort(). ( ,
insertionSort() recQuickSort().)
. -
.
, ,
. ,
, .


: -
. -
, (left right)
,
. ,
.
,
337

. ,
,
.


,
O(N*logN). 6,
, -
,
. 2,
Nlog2N.
Nlog2N
,
QuickSort
Workshop

100 -
.
,
: leftScan rightScan ,
.
,
O(N). ,
. ?
; , -
.
,
N . .
N/2; N.
4 N/4, N,
8 , 16 .. .7.15 1, 2, 4
8 .

,
N/4 , .
.
(, N/8)
. recQuickSort()
; ( )
.. 100 . 7.4.
? 100 2 -
, 100, 50, 25, 12, 6, 3, 1, -
. :
,
.
. 7.4 652 . - -
, 100
2, 100, 6,65. ,
N*log2N -
.
338 7.

. 7.15. ,

7.4.
, ,
.7.15
1 1 100 1 100
2 2, 9 50 2 100
3 3, 6, 10, 13 25 4 100
4 4, 5, 7, 8, 11, 12, 12 8 96
14, 15
5 6 16 96
6 3 32 96
7 1 64 64
: 652

, , , ,
N+2 N/2 . ,
log2N N, .7.5.
log2N, . 7.5, ,
.
. QuickSort

1
Quick-
339

Sort2 Workshop 12 100 ;


, Swaps
Comparisons.

7.5.
N 8 12 16 64 100 128
log2N 3 3,59 4 6 6,65 7
N log2N 24 43 64 384 665 896
: (N+2)log2N 30 50 72 396 678 910
: N/2 log2N 12 21 32 192 332 448

-
QuickSort1 Workshop , ,
QuickSort2. 7.5 (
, ).
1/2 2/3 .


,
. , ,
,
. -
. ,
.

, .
, -
.
,
.
, ( ) .
1. 10 -
.
2. 10 :
, 0,
, 1 9.
.
3. 10 ,
( -
). .
340 7.

, 10 ,
2 ( ).
4. 10 . , -
0, 1 9.
5. . -
, , , 0.
7 ,
. .
421 240 035 532 305 430 124 //
(240 430) (421) (532) (124) (035 305) //
(305) (421 124) (430 532 035) (240) //
(035) (124) (240) (305) (421 430) (532) //
035 124 240 305 421 430 532 //
. -
. ,
, .


, .
10 ? 10
, , -
, -
. 10 10 , -
. .
. -
:
, .
.
,
. -
? .


-
. -
. 10 20 . -
. , ,
5 , 205=100 . 100
2005=1000 . -
, O(N)
, .
341

,
. 10 , -
. , -
,
. ,
O(N logN)
, .
,
.
. ,
, .
, ( ) -
, .

, -
; ..
n- n- .

, .
-
h=3h+1, h 1.
1000 364--
, 121-, 40-, 13-, 4- , ,
1-.
,
O(N (logN)). ,
O(N2) (,
), , O(N logN) ,
.
,
,
.
,
. ,
, ;
.
( while)
.
, .
342 7.

, while .
while .
while,
, .
O(N), N+1 N+2
N/2 .
-
while .
, -
.
; -
.

, .

.

.
.
.
( -
) O(N2).
-
, .
.
O(N2)
.
,
.

while .
O(N log2N) (
).
, ( ),
, .
, ,
.

,
.
, ,
.
343

.
.
1. :
a) ;
b) ;
c) , ;
d) .
2. 100 ,
________.
3.
?
a) 1 h.
b) .
c) .
d) .
4.
2 (/).
5. O-:
_______, _______ .
6. :
a) , ,
;
b) ;
c) ;
d) .
7. _______.
8. 7, :
a) ;
b) ;
c) ;
d) .
9.
(/)
10. , -
:
a) ;
b) ;
344 7.

c) ;
d) .
11.
_________.
12. :
a) ;
b) ;
c) ;
d) .
13. _______ .
14. N partitionIt() -
______ .
15. , , -
5,
(/).

.
.
1. , Partition Workshop
100 , .
2. shellSort.java ( 7.1) ,
n- .
, . -
,
, .
3. shellSort.java ( 7.1) quickSort3.java (7.5)
, ,
.
3.


, -
.
7.1. partition.java ( 7.2) , parti-
tionIt()
( ) . ( quick-
Sort1.java 7.3.) ,
.
.
345

7.2. quickSort2.java ( 7.4) , -


,
. ,
QuickSort2 Workshop,
. ( ,
.)
7.3. 3.2 3
. , -

, ,

.
,
. !
( ), ( ); , -
, . ,
, -
, .
, 0 6.
3. 4,
0 4 (, 3),
5 6. 2,
2 6, 0 1. -
, ,
. .
, ,
.
7.1 .
, , -
,
. ,
.
7.4. k- -
(, 7- ). (.
7.2) .
,
. 7.2 ,
.
?
7.5. ,
.
.
, 10,
(
).
8

, 7, -
, . -
, .
,
, . ,
, .

?
?
, :
.
, ,
, .
, .


, ,
(. 2, ). ,
-
. ;
, ,
.
O(logN).
.
, , -
,
,
. , -
(N/2). ,
, .
, -
.
? 347


, 5, ,

. ,
O(1) ( O-).
, .
,
. ,
N/2 ,
. O(N), . (-
: , ,
.)
,
, ,
. -
, -
. (,
, ,
.)


-
/, , ,
. ; ,
.

?
,
. , ,
.
, . .8.1
. ( Workshop)
, , .
-
.
, , .
13, , 14, .
: , , -
.., ,
. -, Java,
.
348 8.

. 8.1. ( )

( )
. , ( )
, . ,
.
: .
, Java,
( C C++ ).
, -
; , ,
.. , -
. -
, ,
( )
, .
. .

8.1 -
(. ). -
.
. ,
, .
10, 2-3-4.

.
, .
, -
(/), . .8.2
.

, - . -
(path).
? 349

A 0

B -
D E
B C 1
D - E -
B B

D E F G 2

3
H I J
F

H, E, I, J G

. 8.2. ,

().
. ,
( !) . -
. 8.3, , .

. 8.3. ,

( ) ,
. , , (
) .

,
. , ,
.
350 8.

, , ( ).
, .

, -
, ..

( ,
)
.
.

-
. , .
, .

, .
, 0, 1,
2 ..

, .
.
, ,
, . (
.)


,
. ,
.

(. 8.2).
2;

( ).
351

, ,
.

.8.4.

53

30 72

14 39 61 84

9 23 34 47 79

. 8.4.

:
, ,
.

-
. ( -
\ C:\) . ,
, .
.
, .
, ,
. (,
C:\SALES\EAST\NOVEMBER\SMITH.DAT) SMITH.DAT.
( )
.
,
.
; .
. ( -
, ..). , ,
, .
352 8.

?
:
, , .
,
Binary Tree Workshop;
Java.

Binary Tree Workshop


Binary Tree Workshop.
. 8.5. ( ,
.)

. 8.5. Binary Tree Workshop


, , 0 99. ,
. ,
,
999999999.
Workshop ,
Workshop 5 ;
, 5 .
, .
(
).
? 353

Workshop, Fill.
. -
1 31; 15 .
Fill, .
.


, , ,
(.
8.6). .

90

42 95


23 75

10 31 83

7 18 78 87

. 8.6. ( )

-
. ,
. -
(11, 18, 33, 42, 65 ..)
,
.
, , ,
, -
. Workshop,
-
, .
-
Fill, . -

354 8.

. ,
; .
,
,
, .
,

.
.
9, - .

Java
, Java.
,
.
,
.
; , -
, .
.
Java .

,
. ,
, ( 8.1).

Node
. -
, (,
),
. :
class Node
{
int iData; // ,
double fData; //
node leftChild; //
node rightChild; //

public void displayNode()


{
// ( . 8.1)
}
}
? 355

. -
, ,
. displayNode()
, .
Node. -
,
:
class Node
{
person p1; // person
node leftChild; //
node rightChild; //
}

class person
{
int iData;
double fData;
}
,
,
, .

Tree
,
. Tree. : -
Node, . ,
.
Tree , , -
. :
class Tree
{
private Node root; //

public void find(int key)


{
}
public void insert(int id, double dd)
{
}
public void delete(int id)
{
}
//
} // Tree
356 8.

TreeApp
, .
main() , ,
. TreeApp:
class TreeApp
{
public static void main(String[] args)
{
Tree theTree = new Tree; //
theTree.insert(50, 1.5); //
theTree.insert(25, 1.7);
theTree.insert(75, 1.9);

node found = theTree.find(25); // 25


if(found != null)
System.out.println("Found the node with key 25");
else
System.out.println("Could not find node with key 25");
}
} // TreeApp

8.1 main() ,
(,
, ..).

: ,
, .


,
.
, -
, . person
, , , , ..,
, ,
, .. , Workshop
: .
.

Workshop
Workshop ,
( ). , ,
357

. , Workshop

.
, , -
57 (. 8.7). ,
Workshop .
Find. -
. 57 ( ).
Find .
57 < 63
63

27 80
57 > 27

57 > 51
13 51 70 92

57 < 58
26 33 58 82

57 == 57
57 60

. 8.7. 57

Going to left child Going


to right child,
.
. 8.7 .
57 , 63. ,
,
, . -
27; 57 27 ,
27. 51
. 57 51, -
58, 57. 57
.
Workshop

, -
.
- ,
..
358 8.

Java
find(), Tree:
public Node find(int key) //
{ // (, )
Node current = root; //
while(current.iData != key) //
{
if(key < current.iData) // ?
current = current.leftChild;
else
current = current.rightChild; // ?
if(current == null) // ,
return null; //
}
return current; //
}
, , -
current. key.
( ,
), current .
while key iData
( ) . key , current -
, ( )
.


current null, ,
; , , ,
. , null.


while ,
, iData current key; ,
. , , find(), -
.


, . -
Workshop 31 , ,
, .
O(logN), O(log2N) ( 2).
.
359


, .
(.
). ,
. ,
,
.

Workshop
Workshop, Ins.
. ,
45; .
. .8.8,
, .

. 8.8. : ;

45 60, 40 50.
, 45 50, 50 ;
leftChild null. null ,
.
45 ( ) 50
, . 8.8, .

Java
insert() , -
. .
, (.
360 8.

Java). , -
(null) , , -
.
( , ).
, id.
while true, ,
id, ; ,
. (
.)
( -
); , ,
while return.
insert():
public void insert(int id, double dd)
{
Node newNode = new Node(); //
newNode.iData = id; //
newNode.dData = dd;
if(root==null) //
root = newNode;
else //
{
Node current = root; //
Node parent;
while(true) // ( )
{
parent = current;
if(id < current.iData) // ?
{
current = current.leftChild;
if(current == null) //
{ //
parent.leftChild = newNode;
return;
}
}
else // ?
{
current = current.rightChild;
if(current == null) // ,
{ //
parent.rightChild = newNode;
return;
}
}
}
}
}
// -------------------------------------------------------------
361

parent ( current)
null , (50 .8.8). -
, , current
, current null. parent, -
.
-
parent ( , null ).
parent
parent ,
. .8.8 45 50 -
.


.
, ,
. ,
. ,
. (
, .)
: (preorder),
(inorder) (postorder).
, -
, .


-
.
.
(. 6,
).
. .
:
1. .
2. .
3. .
, -
: , ..
,
. ; -
.
362 8.

Java
,
Workshop. inOrder()
, .
. ,
,
. inOrder()
null. inOrder():
private void inOrder(node localRoot)
{
if(localRoot != null)
{
inOrder(localRoot.leftChild);

System.out.print(localRoot.iData + " ");


inOrder(localRoot.rightChild);
}
}
root:
inOrder(root);
,
, .


. -
, (. 8.9),
: (A) (B) (C) .
inOrder() A ( )
inOrder(A). inOrder(A) inOrder()
B ( inOrder() inOrder(B)).
inOrder(B) inOrder() .
B , null.
inOrder() inOrder(null). -
inOrder(): inOrder(A), inOrder(B) inOrder(null).
inOrder(null) , null,
.
inOrder(B)
B
; , -
. inOrder(B) inOrder()
. null, inorder(null)
. inOrder(B)
1, 2 3, ( ).
inOrder(A) -
A. A, inOrder()
363

C, inOrder(C). inOrder(B), inOrder(C)


, 1 -
, 2
C
, 3 . -
inOrder(A) , ,
.

. 8.9. inOrder()

, A,B,C.
-
.
. inOrder()
, .

Workshop
Workshop,
Trav. ( .)
.8.10 , Tree
Workshop. ,
. . 8.1
364 8.

. -
Workshop
.

. 8.10.

8.1. Tree Workshop



()
1 50 () Will check left child

2 30 Will check left child

3 20 Will check left child

4 20 Will visit this node

5 20 Will check right child 20


6 20 Will go to root of previous subtree 20
7 30 Will visit this node 20
8 30 Will check right child 20 30
9 40 Will check left child 20 30
10 40 Will visit this node 20 30
11 40 Will check right child 20 30 40
12 40 Will go to root of previous subtree 20 30 40
13 50 Will visit this node 20 30 40
14 50 Will check right child 20 30 40 50
15 60 Will check left child 20 30 40 50
16 60 Will visit this node 20 30 40 50
17 60 Will check right child 20 30 40 50 60
18 60 Will go to root of previous subtree 20 30 40 50 60
19 50 Done traversal 20 30 40 50 60
365

, -
. , 30
2, 7 8.
, .
, , -
Workshop.


,
, . ,
,
.
.
.
( !)
+, , / *.
, (A, B
C
) . -
.

A +

B C

: A*(B+C)
: *A+BC
: ABC+*

. 8.11. ,

, .8.11

A*(B+C)
, .
( -
4, .)

A*B+C, .
366 8.

?
, -
. preorder()
:
1. .
2. .
3. .
.

8.11 -

*A+BC
.
, ; -
. -
. * A +BC;
+ B C,
B+C. *A
+
BC
( ), -
A*(B+C) .
.

:
1. .
2. .
3. .
. 8.11

ABC+*
. :
* .
A, BC+. BC+
+ .
B

, C

; -
(
B
+
C
).
ABC
+* ( -
) A*(B+C) .

8.1 ,
.

, -
, .8.11, -
. ,
postfix.java (. 4.8 4)
367

. , -
:
1. , .
2. .
:
1. B C.
2. A, .
3. B A.
4. C A.
5. .
,
. ,
, . -
,
, .
.


-
. ,

Workshop
, 8.1. -
, .
,
; ..,
, . -
(.8.12).
:
public Node minimum() //
{
Node current, last;
current = root; //
while(current != null) //
{
last = current; //
current = current.leftChild; //
}
return last;
}
.
, -
, -
, .
368 8.

. , ,

current = current.rightChild; //

63

47 71


22 53 67

11 33 50 60

17 49 51

. 8.12.



. -
, ,
.

find() insert(). ,
:
1. ( ).
2. .
3. .
. ;
; .

1.
, -
, null . -
, (.8.13).
369

10 10

5 5
null


3 7 3 7

. 8.13. , : ;

,
Java
, -
. , -
, .
( C C++ free() delete()
.)

Workshop
, 7 . 8.13. Del
7. , ;
Del 10 5 7.
- .

Java
delete() find() insert(). -
. insert(),
.
, while ; parent
. , delete() false.
public boolean delete(int key) //
{ // (, )
Node current = root;
Node parent = root;
boolean isLeftChild = true;

while(current.iData != key) //
{
parent = current;
if(key < current.iData) // ?
{
isLeftChild = true;
current = current.leftChild;
}
370 8.

else // ?
{
isLeftChild = false;
current = current.rightChild;
}
if(current == null) //
return false; //
}
//
// ...
}
, , -
. , .
, null, -
. leftChild rightChild
null, .
// delete()...
// , .
if(current.leftChild==null &&
current.rightChild==null)
{
if(current == root) // ,
root = null; //
else if(isLeftChild)
parent.leftChild = null; //
else //
parent.rightChild = null;
}
// ...

2.
.
: .
, .
(leftChild rightChild),
. . 8.14.

Workshop
, Workshop .8.14.
71, , -
. Del 71. Del ,
71. 71 63. -
, 63 (
67).
371

Del 71. -
63. , 63, ,
63 52.

80 80

52 52

48 71 48 63

63 67

67

. 8.14. : ;

, ,
, . -
, .
,
, .

Java
.
: , -

.
: ,
, .
:
// delete()...
// ,
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild) //
parent.leftChild = current.leftChild;
else //
parent.rightChild = current.leftChild;
372 8.

// ,
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild) //
parent.leftChild = current.rightChild;
else //
parent.rightChild = current.rightChild;
// ...
, -
.
.
, . ,
,
.
.

3.
. ,
(
). ? .8.15 ,
25 35.
35? 15
30? 30
, .

. 8.15. : ;

, ,
. ,
. , -
373

, .
.
, . 8.15, 30 25.
, : ,
. .8.16 . -
, . ( ,
.)

50 50


25 30

15 35 15 35

5 20 30 40 5 20 40


25

. 8.16. : ;


? (
) ,
. . 8.16 ,
25 30. , 25
35. ; .
, -
.
( ), ..,
.
(.8.17).
?
, .
,
. . , -
,
. , ,
,
.
374 8.

38

26 72

55 90

41 60 78 92

43 74

. 8.17.

, -
(. 8.18).

. 8.18.

Workshop

Workshop
-
. , -
, ( ).
, (
,
).
375

, Del.
. ,
Del . -
.
, Workshop 25
, . 8.15. -
50 25, 30.

Java
getSuccessor(), -
, delNode. ( , delNode
,
, .)
// delNode.
// ,
// .

private node getSuccessor(node delNode)


{
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; //
while(current != null) //
{
successorParent = successor;
successor = current;
current = current.leftChild; //
}
//
if(successor != delNode.rightChild) // ,
{ //
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
}
return successor;
}
delNode, while -
.
while successor delNode.
-
, while
.
getSuccessor() ,
. ,
.
376 8.

, - -
current:
.
.

delNode
successor current, ,
,
, .
:
1. current rightChild ( leftChild) .
.
2. current current
leftChild successor.
delete() :
1. parent.rightChild = successor;
2. successor.leftChild = current.leftChild;
. 8.19 , -
.

. 8.19. , :
;

( else-if,
):
// delete()
else // ,
{
// (current)
Node successor = getSuccessor(current);

// current
if(current == root)
377

root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// current
successor.leftChild = current.leftChild;
} // else
// ( )
return true;
} // delete()
: (-) delete(). -
:
1: current , -
, root successor.
, ( .8.19
),
successor. delete() , current
, , current, ,
Java.
2:
current.
, ? ,
.
,
. ?
, -
, .
, ,
. ,
.
Workshop.
, ,
(, -
,
).
, .
,
.
. ,
.
,
,
.
378 8.


delNode
,
:
1. leftChild
.
2. rightChild -
.
3. current rightChild
successor.
4. current current
leftChild successor.
1 2 getSuccessor(), 3 4
delete(). . 8.20 .

. 8.20. , :
;

:
1. successorParent.leftChild = successor.rightChild;
2. successor.rightChild = delNode.rightChild;
3. parent.rightChild = successor;
4. successor.leftChild = current.leftChild;
( 3 parent. )
.8.20 , . 1 -
. 2
( ,
379

). 1 2 -
if, getSuccessor(). -
:
//
if(successor != delNode.rightChild) // ,
{ //
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
}
return successor;
}
, delete(), getSucces-
sor()
.
3 4 ; 1 2 , -
,
if delete().

?
, ,
. , -
. node
isDeleted. ,
true. , find(), ,
, .
. ,
, .
,
. (,
.)


,
.
? -
. ( , ,
, .) ,
, .
( . .)
. , -
,
380 8.

. 8.2 , -

8.2.

1 1
3 2
7 3
15 4
31 5

1023 10

32767 15

1048575 20

33554432 25

1073741824 30

, 2.
-
2.
N L ,
N 1 2 L,
N = 2L 1.
1 ,
N + 1 = 2L.

L = log2(N + 1).
, -
N 2. O-
O(log2N).
. ,

, ,
.
381

, -
. ,
1000000 , 500000 .
1000000 20 ( ) .
,
500000 . 1000000
20 ,
.
, 1000000
500000 ,
1000000 20 , (-
)
.
,
. ,
. ,
.
, .


leftChild
rightChild, .
.
.
. -
0 , 1
, (.8.21).
( ,
) . -
.
, , null.

. index,

2*index + 1
:
2*index + 2
:
(index-1) / 2
( / ). 8.21
.
382 8.


50
0 50
0
1 25
2 75
3 null 25 75
1 2
4 37
5 62
6 84 37 62 84
3 4 5 6
7 null
8 null
9 31
31 43 55 92
10 43
7 8 9 10 11 12 13 14
11 55
12 null
13 null
14 92

. 8.21.


.
, , .
: ,
;
. ,
,
-
.
. , Tree


Workshop
-
,
.


( )
. insert() -
Workshop -
.
, find() ( ,
) . find()
, ,
( - ) .
.
(, -
tree.java 383

), .
insert(): -
.
Fill Workshop
.

tree.java
-
, .
,
(, , , )
. .
.8.22 .

. 8.22. tree.java

s ( )
i 48 ( ). ,
s . 48
.
s, i, f, d t ,
, , . i, f d ,
. t :
1 , 2 3 .
.
, -
; , . (--)
384 8.

. ,
. ,

.
8.1 , -
Workshop. Workshop,
;
.

8.1. tree.java
// tree.java
//
// : C>java TreeApp
import java.io.*;
import java.util.*; // Stack
////////////////////////////////////////////////////////////////
class Node
{
public int iData; // ,
public double dData; //
public Node leftChild; //
public Node rightChild; //

public void displayNode() //


{
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
}
} // Node
////////////////////////////////////////////////////////////////
class Tree
{
private Node root; // first node of tree

// -------------------------------------------------------------
public Tree() //
{ root = null; } //
// -------------------------------------------------------------
public Node find(int key) //
{ // (, )
Node current = root; //
while(current.iData != key) //
{
if(key < current.iData) // ?
current = current.leftChild;
else // ?
tree.java 385

current = current.rightChild;
if(current == null) // ,
return null; //
}
return current; //
}
// -------------------------------------------------------------
public void insert(int id, double dd)
{
Node newNode = new Node(); //
newNode.iData = id; //
newNode.dData = dd;
if(root==null) //
root = newNode;
else //
{
Node current = root; //
Node parent;
while(true) // ( )
{
parent = current;
if(id < current.iData) // ?
{
current = current.leftChild;
if(current == null) // ,
{ //
parent.leftChild = newNode;
return;
}
}
else // ?
{
current = current.rightChild;
if(current == null) // ,
{ //
parent.rightChild = newNode;
return;
}
}
}
}
}
// -------------------------------------------------------------
public boolean delete(int key) //
{ // (, )
Node current = root;
Node parent = root;
boolean isLeftChild = true;

while(current.iData != key) //

386 8.

8.1 ()
{
parent = current;
if(key < current.iData) // ?
{
isLeftChild = true;
current = current.leftChild;
}
else // ?
{
isLeftChild = false;
current = current.rightChild;
}
if(current == null) //
return false; //
}
//

// , .
if(current.leftChild==null &&
current.rightChild==null)
{
if(current == root) // ,
root = null; //
else if(isLeftChild)
parent.leftChild = null; //
else //
parent.rightChild = null;
}

// ,
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;

// ,
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;

else // ,
tree.java 387

{
// (current)
Node successor = getSuccessor(current);

// current
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;

// current
return true; //
}
// -------------------------------------------------------------
// delNode.
// ,
// .
private Node getSuccessor(Node delNode)
{
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; //
while(current != null) //
{
successorParent = successor;
successor = current;
current = current.leftChild; //
}
//
if(successor != delNode.rightChild) // ,
{ //
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
}
return successor;
}
// -------------------------------------------------------------
public void traverse(int traverseType)
{
switch(traverseType)
{
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;

388 8.

8.1 ()
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
}
System.out.println();
}
// -------------------------------------------------------------
private void preOrder(Node localRoot)
{
if(localRoot != null)
{
System.out.print(localRoot.iData + " ");
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void inOrder(Node localRoot)
{
if(localRoot != null)
{
inOrder(localRoot.leftChild);
System.out.print(localRoot.iData + " ");
inOrder(localRoot.rightChild);
}
}
// -------------------------------------------------------------
private void postOrder(Node localRoot)
{
if(localRoot != null)
{
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
System.out.print(localRoot.iData + " ");
}
}
// -------------------------------------------------------------
public void displayTree()
{
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
"......................................................");
while(isRowEmpty==false)
{
Stack localStack = new Stack();
isRowEmpty = true;
tree.java 389

for(int j=0; j<nBlanks; j++)


System.out.print(' ');

while(globalStack.isEmpty()==false)
{
Node temp = (Node)globalStack.pop();
if(temp != null)
{
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);

if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
}
else
{
System.out.print("--");
localStack.push(null);
localStack.push(null);
}
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
}
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
}
System.out.println(
"......................................................");
}
// -------------------------------------------------------------
} // Tree
////////////////////////////////////////////////////////////////
class TreeApp
{
public static void main(String[] args) throws IOException
{
int value;
Tree theTree = new Tree();
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);

390 8.

8.1 ()
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);

while(true)
{
System.out.print("Enter first letter of show, ");
System.out.print("insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
{
case 's':
theTree.displayTree();
break;
case 'i':
System.out.print("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
System.out.print("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
{
System.out.print("Found: ");
found.displayNode();
System.out.print("\n");
}
// -------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
// -------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
391

}
// -------------------------------------------------------------
} // TreeApp
////////////////////////////////////////////////////////////////
Ctrl

+
C
; -

.


.
.
.8.11,
.
,
: .
, 1952 . -
,
( ).
,
. ,
.


-
(
ASCII
) ( -
, ).
. 8.3
ASCII.
, 8 .

8.3. ASCII-

A 65 01000000
B 66 01000001
C 67 01000001

X 88 01011000
Y 89 01011001
Z 90 01011010
392 8.

. -
,
. E,
.
, Z ,
.
, E

, -
01. ,
: 00, 01, 10 11.
-
?
, . ,
, -
. , E 01, X
01011000, 01011000 , -
01 E X. :
.
, E
. ,
Java, ; ( )
, E. ,
, .
, SUSIE SAYS IT IS EASY. S
.
, ( -
) (. 8.4).

8.4.

A 2
E 2
I 3
S 6
T 1
U 1
Y 2
4
1


. 8.5 -
.
393

8.5.

A 010
E 1111
I 110
S 10
T 0110
U 01111
Y 1110
00
01110

S 10, 00.
01 11 , -
. 3- ? :
000, 001, 010, 011, 100, 101, 110 111. A 010, I
110. ? ,
, 10 00; -
. , 011 U
, 111 E Y. 3-
,
A

I
. , -
4- .
, :
10 01111 10 110 1111 00 10 010 1110 10 00 110 0110 00 110 10 00 1111 010 10 1110
01110

. , ; -
, 0 1.


, , .
. ,
, .
? ,
. . 8.23
.
.
, .
. - -
. , .
394 8.

?
. 0,
, 1 .
A

(010). , , -
A. .8.23.

. 8.23.

. -
, .


, , ; ?
.
Node Tree tree.java 8.1 ( , -
find(), insert() delete(), ).
:
1. Node (. tree.java) , -
. 9 .
: -
. SUSIE SAYS IT IS EASY
. 8.4.
2. .
.
395

3. (. 4). -
, -
. ,
.
:
1.
. ;
.
2. .
3. 1 2. ,
.
, .
.
. 8.24 8.25 ,
SUSIE SAYS IT IS EASY.

. 8.24. , 1
396 8.

. 8.25. , 2


, ; ?
,
. , ,
ASCII 28
. A 0, B 1
Z, 25. 26,
27. (, ,
ASCII
.)
28 .
: 0 A, 1 B ..
.
, , .
. 8.26 , SUSIE SAYS IT
IS EASY.
397

. 8.26. , 3

:

.
, .


, ?
.
. -
: 0 , 1 .
, 0 1 -
. .
,
, -
. ,
.

, .
( ) . -
.
398 8.

.
,
A, A; ,
A, A ( ).
, O(log N).
, .
(-
).
.
, .
,
( ), ( ).

, ,
, .
,
,
.
.
.
, null
.
,
.
, .
A ,
A.
-
,
( ) .
,
.
, -
.
( -
!), , .
,
.
399

.
.
1. ( O-)
?
2. , :
a) , (
) ;
b) , , -
( );
c) (
) ;
d) .
3. (/).
4. 20 . , -
0. 4?
5. :
a) ;
b) ;
c) , ;
d) .
6. Java ______ ______
.
7. -
:
a) (/) -
;
b) (/)
;
c) ;
d) .
8. :
a) ;
b) ;
c) -
( );
d) .
400 8.

9. , _______ .
10. , A S. S
_____, _______.
11. , -
?
a) .
b) .
c)
.
d)
.
12. ,
n _______ .
13. , -
(/).
14. _______ .
15. ?
a)
.
b)
.
c)
.
d)
.

.
.
1. 20 Binary Tree Workshop.
?
2. UML

( - -
) ,
. ,
. ,
. , 1
( ).
, .
3. Binary


Tree

Workshop
-
.
401


,

.
8.1. tree.java (. 8.1) ,
(, A, B
..). .
, , , .
- , , +.
, . ,
. :
;
. , , :
+
+ E
+ D - -
+ C - - - - - -
A B - - - - - - - - - - - - - -
, . (
.) , ,
. , .
, , .
+ .
.
, . -
,
.
find(), insert() delete(), , -
. displayTree() ,
.
8.2. . 8.1,
. ,
.
, +. -
. -
.
, .
8.3. tree.java ,
. ,
, ( -
).
, , . (
,
.) , ABCDEFGHIJ
402 8.

A
B C
D E F G
H I J
, ( ,
). ,
. , -
( 1), n
2*n, 2*n+1. -
, ,
.
. ,
Tree.
8.4. , -
, .8.11 .
Tree tree.java (. 8.1) ParsePost
postfix.java (. 4.8) 4.
. 8.11.
, ,
, -
.
. inOrder()
,
.
8.5. -
. :
, .
.
.
.
.

. , . 8.1, 8.2
8.3. -
String.
.
9
-

8, , -
, -
: ,
.
, ,
.
, .
,
. , -
.
(17, 21, 28, 36,) (36, 28, 21, 17,),
. ,
. -
( ).

: -
.
.
, 2-3-4
2-3 10, 2-3-4. , -
, 2-3-4
- .


- ,
. -
. , -
( , ..)
, -
. -
, . -
2-3-4 ,
10. , ,
2-3-4, .
404 9. -


-
RBTree Workshop. ,
. , -
, , .
- ,
. , ,
, .
.


, , (top-
down) .
.
.
, ,
. ,
.

- , ,
. Binary Tree
Workshop 8 (
RBTree
!). -
Fill , .
, .
, . 9.1.

10

20

30

40

50

. 9.1. ,
405

.
, , ,
.
. , ,
, -
.

O(N)
. -
. ,
,
() .
O(N) O(logN), . 10000-
5000 ,
14.

.
, -
. Binary Tree Workshop
8 31 ,
, (. 9.2).

. 9.2.

, -
, .
Binary

Tree

Workshop

-
,
406 9. -


. ,
,
. , -
3 .

.
.
- O(N)
O(logN) .


O(log N), , -
,
( ). ,
-
( ).
- ( -
, ). ,
.

. -
.

-
? ,
:
.

.


- ,
. ; ,
. , :
, -
-. . -
,
(, isRed).
RBTree Workshop .
, Binary Tree Workshop ,
.
407

,
. ( . 9.3)
, -
. ( ,
.)

-
( ) , -
- . -
, . :
1. .
2. .
3. , (
).
4.
.
, 4, -
- . ,
, , -
. , .
.
4 ,
.
. ,
, -
. .
.
RBTree

Workshop

, -
. , ,
- .


, -
? - .
,
. , -
50, 50, 50, 50
, .
.
-
.
,
.
408 9. -

. -
, .


, ( ) -
. , -
? ( !) :
.
.

( ). , -
.
, -
. RBTree Workshop .

RBTree Workshop
. 9.3 , RBTree Workshop
. (
, .)
RBTree .
, ,
.

. 9.3. RBTree Workshop


RBTree Workshop 409


. ,

. , ;
.

Start
RBTree Workshop (
Start) . -
, -
.
50.
.

Ins
Ins , Number,
. ( , .
Flip.)
: Ins
; Binary Tree Workshop ,
. ,
. RBTree

, .
,
.

Del
Del , Number. -
Ins, ;
.
Del Ins , -
Tree Workshop.
: ,
( ) , - -
, , , .
410 9. -

Flip
-
( , ),
Flip , . -
, . ,
.
(-
2), .

RoL
RoL . ,
.
.
RoL. .

RoR
RoR





.

, -
, , , -
.

R/B
R/B , .
, , . (
R/B ; Flip, -
.)


, -
- . -
, 1 4.
, , .
.

Find?
- ,
. -
, ( ) ,
Workshop 411

,
.
Find RBTree ,
, -
.

Workshop
, , RBTree,
. ,
. -
. .

1.
Start, .
, 50.
, (,
25), Number Ins.
, - ,
- .
, , -
75. ,
- () ,
. . 9.4.

. 9.4.

(
).
- , . ,
, -
. ,
( 3), - ( 4),
412 9. -

, , 3
, .
,
, , 4.
, , 3 ( , -
) , 4
( ).

2.
. , .9.4.
(50),
; .
RoR. (. 9.5).

25

50

75

. 9.5.

,
,
.
: ;
, . , -
- , 2 (
). ,
. 25,
( 25 ),
RoL. .9.4.

3.
. 9.4, 50
25 75. , ()
, .
. ,
.
Workshop 413

, ,
.
(
); Flip.
.
, : -
, 2.
, - .
Ins. .9.6 ,
12.

50

25
75

12

. 9.6.

- - .
, , -
, ().
- .

4.
, , -
. . 9.6 .
, - -
, - ,
. , (
)? -
, -
.
6 . 9.6. : -
. 3
(.9.7).
, 3 ?
- . -
, 6. R/B.
.
. ,
: . 6
414 9. -

, 75 . 4
. ?

50

25
75


12
3


6
4

. 9.7. ,

.
, , .


RBTree Workshop .
, . -
, ? -
- ( )?
, (50, 60,
70, 80, 90), Start ,
(50, 40, 30, 20, 10). ;
, .
.
?

-

, ,
- . , -
. - -
. ,
( 4), -
( 3).
, .
415


4: ,
, .
-
( , -
, ). , . 9.8 50 25
25 ( )
, 6 75 . -
4,
.

50

25
75

12

. 9.8.


. , . 9.8 50 1, 25 1,
12 2 ..

, -
. , ,
.
. , .
:
,
;
.
,
,
416 9. -

. ,
; (.
) .
: -
, .
; .
(,
),
.


2 .
, . -
.

?
. -
; .
.
, .
, . , -
.
2 , , ,
, .


, -
. ,
. ,
.


,
. Start, ( -
50) : 25,
75, 12, 37.
12 -
. Flip;
. Ins, 12. ,
37. , . 9.9, a.
417

50

25 75

12 37

25

12 50

37 75

. 9.9.

. (
!) RoR. .
12 25 , 50 75 .
? 37 25, ,
50. , , 37
. . 9.9, .
4; , .
. 9.9, 37
50 ( 12 ). , -
, (
),
.


, ,
. Start -
50, : 25, 75, 12, 37, 62, 87,
6, 18, 31, 43 ( ). ,
, Flip. -
. 9.10, .
418 9. -

50

25 75

12 37 62 87

25

6 18 31 43

25

50
12

37 75
6 18

25

31 43 62 87

. 9.10.

50, RoR. !
. . 9.10, . -
:
(50) .
(25) .
12 .
37 50.
75 .
(
), .
, RoR RoL (
419

). , -
( , 37).
. 9.10 .
:
. .
, . -
, .


, .

Workshop
, -
RoR RoL. ,
- , -
.
, ,
.
, , .
,
, .

- .


, ,
- - -
.


, -
. , -
; .
X, P G
.
X
, - . ( -
X ,
- .)
X .
P X.
G X ( P).
420 9. -

, -
( 2) -
.
- ( 3). X,

P
. -
, X G.

.
X, P ,
. P , : X
, G.
( ). X ,
, .
.
.
:
1. .
2. .
3. .
,
3 2.
, , 1 2
3, 2 3.


-
, :
,
.
- -
. -
3; .
, ,
, .
, -
. : ,
,
, (
, ).
- ? -
(, )
P ( Parent). P X1 X2.
. 9.11, .
421

P P

X1 X2 X1 X2

. 9.11.


. 9.11, . -
P
.
P
,
X
1, -

X
2.
P
, (-
P, X1 X2) .
P ,
X

1 X

2; , -
, . ,
4.
,
.
3.

3
4, 3 (
) . P
, P
.
P
, -
.
,
. , .


? ,
, 2.
- ? ,
-,
. , 3 . ,
422 9. -

, ,
. , 4 .

,
( ), -
, (.
).
.


- .
, -
.
, ( X)
. . 9.12, X
P G.

. 9.12.
423

, X ,
P


G
. -
, X , P, P
G (. 9.12, ), P,
P G (. 9.12, ). , X

-
, P
G (. 9.12, ).
. 9.12 (
) , - -
.
, - , -
X . ,
( -
/ ).

1 2

3
. 9.13.

-
, .
,
.
. 9.13 (, X ):
424 9. -

1. P .
2. P , X G.
3. P , X G.
, .
, .

1. P
P , . .
, - ( 3) , -
( 4). , -
. , .

2. P , X
P , X ,
.
RBTree Workshop , . 50
25, 75 12. 12 -
.
6 X.
. 9.14, . Workshop

-
, . -
.

. 9.14. P , X G
425

-
(, ) :
1. G (25 ).
2. P (12).
3. G (25) ,
X(6). .
,
R/B. ,
RoR . ,
Workshop , - .
, , (.9.14, ).

X
. -
, X ,
. 50, 25, 75, 87, 93 (
). , 75 87 -
75. .

3. P , X
P , X ,
. : RBTree
Workshop 50, 25, 75, 12, 18. ( ,
12 .)
. 9.15, .
: 18 . ,
,
.
. -
G (25), 2, X
(18) , -
. (
12, -
.) .
X ,
. X
, . 9.15, . -
1, -,
. . 9.15, .
. -
- ( ,
, ,
). :
1. X (25 ).
2. X ( ; 18).
426 9. -

3. , P
( 12), , X (
).
4. , X (25),
, X ( ).

. 9.15. P , X G

-
, ( ).
2, , P
, G.

?

? , X S P.
, X.
427

P X ( 1). P ,
( 3).
S,
S . , X
, , X ,
P .
: G, P, U, P
X. .
, P X ;
, P . U
( , G P,
, G U).
,
.
, -
( , 2 3 X
).


,
- .
:
.
, .
, - -
. ,
- .
, .
-
-
(, AVL-). ,
.


, :
. , -
, . -
,
, .
,
3 (
). , -
.
428 9. -

, 2
3 . -
( , 1, -
).


, - -
- -,
-.
50, : 25,
75, 12, 37, 6 18. 12 6
. Flip. ,
- 25 -
12. . 9.16, .

. 9.16.

, , -
, (. ), -
.
429

, ,
(12 )
X
. , -
, X
, . -
.
X (25 ) P, P,
X

(50),
G
. , -
2:
1. G (50 ).
, .
2. P (25).
3. G (50) ,
X(6). .
!
. , -
. 3
. 6, ,
, .
( 50). . 9.16, ,
3.


-
X ,
.
( 3).
Start RBTree Workshop,



50.



25, 75, 12, 37, 31

43.
12 31 -
( 37).
37 25 ,
. Ins.
G 50, P 25, X
37 (. 9.17, ).
- -
, 3:
1. G (50 ).
, .
2. X (37).
3. , P
(25). . 9.17, .
4. , X (50),
, X ( ).
430 9. -

. 9.17.

28. 25
50 . . 9.17, .
- ( -
, ) .

, , , -
, . -
,
- 431

-
.
, ,
. (
) -
. , , ,
. ,
. ,
. , -
C.

-
- , , -
, O(log2N).
-
, - .
-
- ( ).
, (. ),
- log2N ,
, 2 log2N .
-

. .
, O(log2N), -
.
-
, , -
- -
. , -
, -
O(N).

-
- ,
(, ): ,
. ,
. ,
.
Node (
boolean).
432 9. -

tree.java ( 8.1 -
8). ,
. ,
( -
).
, 3 .
, : ,
.
, , tree.java, -
, . -
.
,
(, , -
). 3,
, (
4, ).
, ,
, ,
. RBTree Workshop
, -
.


AVL-
, : - -
. AVL- :
.
. , -
.
,
. 1, -
.
, ,
.
.
AVL- O(logN),
. ( ) -
: , AVL-
-
.

(multiway) , .
2-3-4 -
433

.
,
.

, -
.

, O(N).
- -
: ( ).

, - .
( ) .

.
.
,
.
,
.
-
, . -
- .
-
-. ,
, - .
(
).
- -

.

.
.
1. -
________ .
434 9. -

2. :
a) ;
b) ;
c) , ;
d) .
3. -
(/).
4. :
a) , , ;
b) , ;
c) ,
;
d) ,
( ).
5. - ?
a) -
;
b) , ;
c) ;
d) - -
.
6. :
_______ _______ .
7. _______ .
8. ?
a)
.
b) .
c) - .
d) .
9. ________,
_______ , .
10. ? -
:
a) ;
b) ;
c) ;
d) .
435

11. ______ ______ .


12. :
a) , -
;
b) , -
;
c) ( );
d) ,
.
13. ,
(/).
14. , :
a) , ;
b) , ;
c) , ;
d) , .
15. -
(/).

.
.
1. ( -)
, -
( ,
).
2. RBTree Workshop ,
1, .
3. , -
- 1, 2 3 4 .

, - -
. -
- .
tree.java (. 8.1) 8.
10
2-3-4


. -
. 2-3-4,
, ,
.
2-3-4 . -,
, - . -
, - , -
. - ( ), B-.
B- ,
( -
;
). B- .
B- .

2-3-4
2-3-4. -
, 2-3-4 Workshop

-
2-3-4 Java.
2-3-4 - .
. 10.1 2-3-4. ( -
) ,
.
50

30 60 70 80

10 20 40 55 62 64 66 75 83 86

. 10.1. 2-3-4

,
, . 2-3-4
.
2-3-4 437

2-3-4 ?
2, 3 4 ,
. -
:
.
.
.
, -
.
, L
D :
L = D + 1.
2-3-4.
, , ,
. .
2-3-4 , -
4.
2-3-4 1-2-3-4?
, ? (. 8,
9, - )
2,
. 2-3-4
( ):
.
; null.

. 10.2. 2-3-4
438 10. 2-3-4

2-3-4 .
(
).
. 10.2. -
2-, 3-,
4-, , 1-, .

2-3-4
0 2,
0 3, . 10.2. -
; .

. ,
, , ;
, , -
, . 2-3-4
, :
, 0,
0.
, 1,
0, 1.
, 2,
1, 2.
, 3,
2.
. 10.3. 2-3-4 -
, .

A B C


A C
A B B C

. 10.3.

. 10.1. 2-3-4, -
( ).
, .
, . -
, ( ). ,
2-3-4 .
2-3-4 439

2-3-4
.
-
, .
, 64
. 10.1, .
. 64 50, 1,
60/70/80. ( , 1 ,
.)
, .
64 60, 70, 1.
62/64/66.

,
. , -
,
,
.
2-3-4 , -
.
. ,

. . 10.4 18 -
2-3-4.

. 10.4. : ;
440 10. 2-3-4


, -
. 23 ,
18.


,
. ; -
. 2-3-4,
, 2-3-4,
.

A
, B


C
. -
(,
; ).
. ( )
.
C .
B .
A .
-
.
. 10.5.
4- 2-.

. 10.5. : ;
2-3-4 441

:
. .
, -
.
.



, :
, .
, .
C .
B .
A .
-
.
. 10.6 , .
, . ,
.
4- 2-.
.
. 10.6 41 .

. 10.6. : ;
442 10. 2-3-4


,
.
, ,
B . ,
, ,
, .
. 10.7 .
: .

. 10.7. 2-3-4

Tree234 Workshop
Tree234 Workshop ,
2-3-4. . 10.8 , -
.
Tree234 Workshop 443

. 10.8. Tree234 Workshop

Fill





Tree234 Workshop





7


-
. Fill
( 0 45). Fill .
.
45 , -
, .

Find
,
, Find.
, -
.
Went to child number 1 (
1). , 0 3 ,
0 2.
, .
. -
,
. -
, ; , ,
.
.
, .
444 10. 2-3-4

Tree234 Workshop
. ,
Press any button .

Ins
Ins , -
. .
, , .
. ,
; -
. ,
( , - ). ,
, .

Zoom
2-3-4
. Tree234 Workshop 4 ,
64 ,
.
, -
: . (
, ;
.) , Zoom
(. 10.9).

. 10.9. 2-3-4
Tree234 Workshop 445

,
. ,
( -
Zoom), . ,
, ,
. ,
.

Zoom , -
, .


:
.
,
: 16 , 64 . -
, ( ,
).
, .
,
, . ,
, ,
. , -
. ,
.
0 () 85 ( -
).
(..10.8). ,
, -
.
. 10.10 .
1,
5 6. 2,
9 10 (. 10.11).
,
, .
, ,
.
Find Ins -
,
.
446 10. 2-3-4

. 10.10.

. 10.11.

Tree

234
Workshop
-
2-3-4. , .
,
. Ins
.
,
. , ( -
..). ,
, Zoom,
.
2-3-4 Java 447

? -
, .
1 + 4 + 16 + 64, 85 (
85 ).
, 255 .
.
, , -
.
, ,
;
, , .
50.
Fill 45, -
.

2-3-4 Java
Java

-, 2-3-4. -
tree234.java .
, ; , ,
.
: DataItem, Node, Tree234 Tree234App. -
.

DataItem
DataItem , .
-
, ..,
DataItem long.
: -
. : /27. (
display Node .)

Node
Node : childArray itemArray.
; .
DataItem,
.
: itemArray
.
448 10. 2-3-4

, (. 2, ).
-
, .
(numItems)
(parent) .
; ,
. , -
.
Node
, ,
. findItem(), insertItem()
removeItem(), .
, -
; (
); ( -
). -
find() insert() Tree234, .
display -
/ /27/56/89/, /14/66/ /45/.
Java null ,
, Node .

Tree234
Tree234 . root
Node. , -
- .

find().
, findItem()
, , . -
,
. find() , -
, 1.
, , find() getNextChild(),
,
.

insert() , find()
, . , -
, ; , -
2-3-4 Java 449

, .
. ( ,
.)

split() . ,
, .
.
; .
newRight.
. ,
: .
.
,
.

A
,
B
C

. B

. -

,
. newRight (.
.10.5 10.6).
newRight. -
C, 2 3,
. , split()
.

Tree234App
Tree234App main() .
-
s ( ), i ( ) f ( -
). :
Enter first letter of show, insert, or find: s
level=0 child=0 /50/
level=1 child=0 /30/40/
level=1 child=1 /60/70/

Enter first letter of show, insert, or find: f


Enter value to find: 40
Found 40

Enter first letter of show, insert, or find: i


Enter value to insert: 20
Enter first letter of show, insert, or find: s
level=0 child=0 /50/
450 10. 2-3-4

level=1 child=0 /20/30/40/


level=1 child=1 /60/70/

Enter first letter of show, insert, or find: i


Enter value to insert: 10
Enter first letter of show, insert, or find: s
level=0 child=0 /30/50/
level=1 child=0 /10/20/
level=1 child=1 /40/
level=1 child=2 /60/70/
, -
. (0-
) .
, ,
, , -
..
: 20 10.
( 0 ). . 10.12 -
,
s.

. 10.12. tree234.java

tree234.java
10.1 tree234.java -
. - ,
,
. -
Tree234App, Tree234, Node, DataItem.

10.1. tree234.java
// tree234.java
// 234-
// : C>java Tree234App
import java.io.*;
////////////////////////////////////////////////////////////////
2-3-4 Java 451

class DataItem
{
public long dData; //
//--------------------------------------------------------------
public DataItem(long dd) //
{ dData = dd; }
//--------------------------------------------------------------
public void displayItem() // "/27"
{ System.out.print("/"+dData); }
//--------------------------------------------------------------
} // DataItem
////////////////////////////////////////////////////////////////
class Node
{
private static final int ORDER = 4;
private int numItems;
private Node parent;
private Node childArray[] = new Node[ORDER];
private DataItem itemArray[] = new DataItem[ORDER-1];
// -------------------------------------------------------------
//
public void connectChild(int childNum, Node child)
{
childArray[childNum] = child;
if(child != null)
child.parent = this;
}
// -------------------------------------------------------------
//
public Node disconnectChild(int childNum)
{
Node tempNode = childArray[childNum];
childArray[childNum] = null;
return tempNode;
}
// -------------------------------------------------------------
public Node getChild(int childNum)
{ return childArray[childNum]; }
// -------------------------------------------------------------
public Node getParent()
{ return parent; }
// -------------------------------------------------------------
public boolean isLeaf()
{ return (childArray[0]==null) ? true : false; }
// -------------------------------------------------------------
public int getNumItems()
{ return numItems; }
// -------------------------------------------------------------
public DataItem getItem(int index) // DataItem
{ return itemArray[index]; } //

452 10. 2-3-4

10.1 ()
// -------------------------------------------------------------
public boolean isFull()
{ return (numItems==ORDER-1) ? true : false; }
// -------------------------------------------------------------
public int findItem(long key) //
{ // ( )
for(int j=0; j<ORDER-1; j++) //
{ //
if(itemArray[j] == null) // -1
break;
else if(itemArray[j].dData == key)
return j;
}
return -1;
}
// -------------------------------------------------------------
public int insertItem(DataItem newItem)
{
// ,
numItems++; //
long newKey = newItem.dData; //

for(int j=ORDER-2; j>=0; j--) // ,


{ //
if(itemArray[j] == null) // ,
continue; //
else // ,
{ //
long itsKey = itemArray[j].dData;
if(newKey < itsKey) //
itemArray[j+1] = itemArray[j]; //
else
{
itemArray[j+1] = newItem; //
return j+1; //
} //
}
} // ,
itemArray[0] = newItem; //
return 0;
}
// -------------------------------------------------------------
public DataItem removeItem() //
{ //
// ,
DataItem temp = itemArray[numItems-1]; //
itemArray[numItems-1] = null; //
numItems--; //
return temp; //
} //
2-3-4 Java 453

// -------------------------------------------------------------
public void displayNode() // "/24/56/74/"
{
for(int j=0; j<numItems; j++)
itemArray[j].displayItem(); // "/56"
System.out.println("/"); // "/"
}
// -------------------------------------------------------------
} // Node
////////////////////////////////////////////////////////////////
class Tree234
{
private Node root = new Node(); //
// -------------------------------------------------------------
public int find(long key)
{
Node curNode = root;
int childNumber;
while(true)
{
if(( childNumber=curNode.findItem(key) ) != -1)
return childNumber; //
else if( curNode.isLeaf() )
return -1; //
else //
curNode = getNextChild(curNode, key);
}
}
// -------------------------------------------------------------
//
public void insert(long dValue)
{
Node curNode = root;
DataItem tempItem = new DataItem(dValue);

while(true)
{
if( curNode.isFull() ) // ,
{
split(curNode); // .
curNode = curNode.getParent(); //
//
curNode = getNextChild(curNode, dValue);
}

else if( curNode.isLeaf() ) // ,


break; //
// ;
else
curNode = getNextChild(curNode, dValue);
}

454 10. 2-3-4

10.1 ()
curNode.insertItem(tempItem); // DataItem
}
// -------------------------------------------------------------
public void split(Node thisNode) //
{
// ,
DataItem itemB, itemC;
Node parent, child2, child3;
int itemIndex;

itemC = thisNode.removeItem(); //
itemB = thisNode.removeItem(); //
child2 = thisNode.disconnectChild(2); //
child3 = thisNode.disconnectChild(3); //
Node newRight = new Node(); //

if(thisNode==root) // ,
{
root = new Node(); //
parent = root; //
root.connectChild(0, thisNode); //
}
else //
parent = thisNode.getParent(); //

//
itemIndex = parent.insertItem(itemB); // B
int n = parent.getNumItems(); // ?

for(int j=n-1; j>itemIndex; j--) //


{ //
Node temp = parent.disconnectChild(j); //
parent.connectChild(j+1, temp); //
}
// newRight
parent.connectChild(itemIndex+1, newRight);

// newRight
newRight.insertItem(itemC); // C newRight
newRight.connectChild(0, child2); // 0 1
newRight.connectChild(1, child3); // newRight
}
// -------------------------------------------------------------
//
public Node getNextChild(Node theNode, long theValue)
{
int j;
// , ,
int numItems = theNode.getNumItems();
2-3-4 Java 455

for(j=0; j<numItems; j++) //


{ // ?
if( theValue < theNode.getItem(j).dData )
return theNode.getChild(j); //
} // ,
return theNode.getChild(j); //
}
// -------------------------------------------------------------
public void displayTree()
{
recDisplayTree(root, 0, 0);
}
// -------------------------------------------------------------
private void recDisplayTree(Node thisNode, int level,
int childNumber)
{
System.out.print("level="+level+" child="+childNumber+" ");
thisNode.displayNode(); //

//
int numItems = thisNode.getNumItems();
for(int j=0; j<numItems+1; j++)
{
Node nextNode = thisNode.getChild(j);
if(nextNode != null)
recDisplayTree(nextNode, level+1, j);
else
return;
}
}
// -------------------------------------------------------------
} // Tree234
////////////////////////////////////////////////////////////////
class Tree234App
{
public static void main(String[] args) throws IOException
{
long value;
Tree234 theTree = new Tree234();

theTree.insert(50);
theTree.insert(40);
theTree.insert(60);
theTree.insert(30);
theTree.insert(70);
while(true)
{
System.out.print("Enter first letter of ");
System.out.print("show, insert, or find: ");

456 10. 2-3-4

10.1 ()
char choice = getChar();
switch(choice)
{
case 's':
theTree.displayTree();
break;
case 'i':
System.out.print("Enter value to insert: ");
value = getInt();
theTree.insert(value);
break;
case 'f':
System.out.print("Enter value to find: ");
value = getInt();
int found = theTree.find(value);
if(found != -1)
System.out.println("Found "+value);
else
System.out.println("Could not find "+value);
break;
default:
System.out.print("Invalid entry\n");
}
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//-------------------------------------------------------------
} // Tree234App
////////////////////////////////////////////////////////////////
2-3-4 - 457

2-3-4 -
, 2-3-4 - (. 9)
- . , , -
.
, ,
, . ,
.
, 2-3-4
- , -
, .
2-3-4;
- .

2-3-4
-
2-3-4 - -
(. 10.13):
2- 2-3-4 -
(. 10.13, ).
3- (. 10.13, ).
: W X, X Y,
Y W. ,
, . , -
.
4- (. 10.13, ).
W X,
Y


Z
. , -
, .
. 10.14 2-3-4 - ,
.
, 3- 4-. -
. ,
:
/, ( -
) . , 3-
2-3-4 - ,
4- .
- 3- 2-34;
2- 2- . -
4-.
458 10. 2-3-4

. 10.13. 2-3-4 -

. 10.14. 2-3-4 () - ()
2-3-4 - 459


-
2-3-4, , ,
. 2-3-4
, -
.

4-
2-3-4 , -
4- 2-. - -
. ?
. 10.15, 4- 2-3-4 ; . 10.15,
. 2-, 4-,
3-.
. 10.15, - 2-3-4
.10.15,. 4-. -
- , .10.15,.
40 60 , 50 . , 50
3-; 3-,
. 10.15, .

. 10.15. 4-

, 4- 2-3-4
- .
460 10. 2-3-4

3-
3- 2-3-4 -
, . 10.13, . -
. ,
, , , -
, .
, -
. .
. 10.16, 2-3-4, . 10.16,
- , -
2-3-4. 3-,
: . 10.16, 80,
. 10.16, 70.

. 10.16. 3- : 2-3-4; ;
2-3-4 461

, ,
. -
- . 10.16, ,
( ). ,
, . 10.16, .
, , -
2-3-4 -
. ,

.

2-3-4
2-3-4 , -
, - 2-3-4
.

8, - -
( ,
). - (-
) log2(N+1),
.
2-3-4 ,
2-3-4 ( ), -
. , . 10.14 2-3-4
, - .
, 2-3-4 .
,
log4N. 2 4 2.
, 2-3-4 -
, . -
, 2-3-4 - log2(N+1) log2(N+1)/2.
2-3-4
- .
, ,
. -
, , -
M ( ).
Mlog4N. O-
.
462 10. 2-3-4

, 2-3-4 -
. 2-3-4 -
(, - )
, O(logN).


2-3-4
.
( tree234.java), -
.
2/3 1/2 .
1/3 1/4 -
; , 5/7 .
, 2/7 -
.
, -
, -
34
.
- -
, ,
. , -
. ,
- 2-3-4
.
Java ,
2-3-4 - -
, 2-3-4 . ,
, -
- 2-3-4
.

2-3
2-3: -, -
, -,
. , 2-3
B-, . , ,

.
2-3 2-3-4, , (
)
2-3 463

. -
, . 1970- . B- (
2-3-4) 1972 .
2-3 2-3-4.
, , .
.
2-3 ,
. 2-3-4,
,
.


,
2-3-4, . -
, 2-3 ,
.
:
, ,
. 2-3-4
, .
2-3 . ?
, .
2-3-4 ,
2-3 .
, .
, , , -
,
.
: , . ,
( ).
. 10.17.

. 10.17.

, . -
, , -
, (. 10.18).
464 10. 2-3-4

. 10.18.

( ) , -
. , -
. ,
, (. 10.19).

. 10.19.

. 10.20 ,
.

. 10.20.
2-3 465

2-3 Java

-
.
. (
).

, . ,
. , -
. , -
. split(). -
.
split() .
split() , , -
. ,
- . split()
split().
.
2-3-4 , 2-3
; -
.

. 10.21. : 0; 1;
2
466 10. 2-3-4

, ,
()
.
.
, (0, 1 2) .
. 10.21.
, ,
, .


2-3-4 ,
.
B- ,
(, ).
.
:
. B-; ,
.
,
, B-.
,
.
.
, ,
,
, .


, , ,
.
,
.
. ,
, ;
.
, : -
. ( ) -
.
.
.
467

,
. -
.
. , -
, 500000.
, , , -
. 512.
500000 512, 256000000 ,
256 . , ,
.
, . -
, :
, ?
. -,
, -
. -, -
. .


. -
, ,
( ).
. -
, -
.
,
/ .
-
; , -
( ).
/
.
.
10000 ,
. ( )
.
,
10 . 10000 , -
.
,
,
.
468 10. 2-3-4


/ ,
( ) ,
. , -
.
,
; .
-
.
, , 2.
,
8192 (213). ,
256000000/8192 = 31250 .
/
, .
100 (8192 )
, 100 . 8200 ,
(16384) . ,
, .
512 ,
16 (8192/512), . 10.22.
,
16 ( , ).

. 10.22.
469

, ,
.
, , -
; -
, .
, ,
512 .
/ ,
. , -

. ,
(
).



(,
). Aardvark .. (. 10.23).

. 10.23.

(, Smith),
.
. 16
8192 , .
(, Keller)
, 3/4 (Prince)
; , -
1/4 (DeLeon).
, .
2, -
log2N , 500000 19 .
, , 10 ,
190 , 2/10000 ,
.
, , .
,
, .
470 10. 2-3-4

16 ,
.
, ,
, , -
.
31250 . 2 15;
,
15 .
. -

,
, . -
,
, 16 . -
.
, 13 (15-2),
10 130 , 1/7 .
, , .

, ( ) -
. -
, ,
.
:
. -
, .
, , ,
, .
.
.
, ,
.
. ,
.
31250 , , /-
( ) 15625 .
/ 10 ,
5 .
.
:
. ;
?
, .
471

, .
, 2,5 -
.
.

B-
, -
? , -
. ?
, ,
. -
2-3-4,
; B-.
B- .
.. 1972 . ( , 2-3 2-3-4
B
- 3 4 ,
B
- -
.)


? ,
.
,
. -
.
? 512-
8192-
16.
( , ). ,
( , ),
C++
, . ,
, ( 0 31249
). int 4--
, ,
.
16512- ,
.
15, , , -
, (
) 507 .
17 (
), 68 (17 4). ,
16 507- 12
472 10. 2-3-4

(5076 + 68 = 8180).
. 10.24.

. 10.24. B- 17

,
2-3-4. B- 2-3-4,

. B

- -
. 17,
B- 17- .

,
2-3-4, . , ,
. 15 (
), 0. -
,
.
, .
, -
.

B- 2-3,
2-3-4. , 2-3-4
. ,
, . B-
.
473

B- ,
, ,
. -
2-3-4 :
:
, .
, , 2-3.
2-3, ,
, .

B
- (. 10.25). -
, ; ,
B- 5.

. 10.25. - (. . 474)
474 10. 2-3-4

. 10.25.

. 10.25, ; 20, 40, 60 80


. 70
. ,
( 2-3-4): .
, ,
. -
, . . 10.25
(20, 40, 60, 70,
80 ).
(60 )
. ( , -
.) ,
. . 10.25, .
( -
, .)
. 10.25, 10 30.
, . 10.25, . 15
; . 10.25, . 20 -
.
75, 85 90. -
, ,
80 . . 10.25, .
475

, 25, 35 50. -
, ,
35 (. 10.25, ).
. , -
,
,
. 22 27
- , . 10.25, .
32 (
). , (. 10.25, ). -
27, , ;
, . 10.25, .
: ( ) -
. , -
,
.

B-
,
B- .
500000 .
B- ,
8 9 .
log9N ( N 9), N = 500 000. 5972, ,
6 .
, B- 500000
6 .
10 , 60 ,
6/100. , -
.
, .
, B- 6 ,
16. , 500000 -
19, 2-3-4 10 . -
,
.
B- , ,
B- .
B-, .
.

6 .
7 .
, . -
, .
476 10. 2-3-4

;
, , . , -
, 5 12. -
500000 , ,
.
B-
. - .
,
.
, . ,
, -, .


. -
/, . ,
500000 ( 512 16 )
31250 . ,
, :
(, Jones).
, Jones.
0 31249.

. 10.26.

, 28 (
), 4 ( int Java).
477

, 32 1/16 -
.
. -
.
, ,
.
. 10.26.


, .
, .
500000 . -
32- , , 32500000,
1600000 (1,6 ).
. , -
.
. ( , )
.

-
, . -
, 19 .
20 , 4/10000 .

, , -
10 .



















.
-
,
, ,
.
-
. , -
,
250000 32 2, 16 .
. ( :
, .)
, -
, , 2-3-4 -
. .
478 10. 2-3-4

,
.








-

B-.

. , -
, . -
.


-
.
, , ,
.. -
, -
. ,
,
, .


, -
.
B-. .
.
;
, . -
.
B-, n -
n1 .
. -
. .


: -
. ,
Frank -
Springfield, 7.
, , .
, -
, ,
Frank Springfield. (
)
.
479


.
, ,
, ,
.
6, ,
, .
(
),
. -
,
.
,
, , ,
. ,
, -
. ,
.

. 10.27.
480 10. 2-3-4

,
.
, . 2--
4- .
,
.
. 10.27 .
4 4 , 16 . ,
. (,
.) . 10.27 -
; .


.
- -
, (
).
. 10.27, .
.
, ; ,
.

. -
2- -
. , 2-9-11-14 4-12-13-16
2-4-9-11-12-13-14-16, 3-5-10-15 1-6-7-8 1-3-5-6-7-8-10-15.
. 10.27, .
.
8 -
16 , 2
(.10.27, ). . ,
, log2N.

( 2 3 . 10.22).



, . ,
arr1, arr2 arr3,
.
2-9-11-14 arr1, 4-12-13-16
arr2. arr3 .
481

arr3 ,
. ,
, arr3 . -
, arr3 .
.

. 10.28. 3

1:
1. 2-9-11-14 arr1.
2. 4-12-13-16 arr2.
3. 2, 4, 9, 11 arr3; .
4. 12, 13, 14, 16 arr3; .
2:
1. 3-5-10-15 arr1.
2. 1-6-7-8 arr2.
3. 1, 3, 5, 6 arr3; .
4. 7, 8, 10, 15 arr3; .
482 10. 2-3-4

3:
1. 2-4-9-11 arr1.
2. 1-3-5-6 arr2.
3. 1, 2, 3, 4 arr3; .
4. 5, 6 arr3 ( arr2 ).
5. 7-8-10-15 arr2.
6. 7, 8 arr3; .
7. 9, 10, 11 arr3 ( arr1 ).
8. 12-13-14-16 arr1.
9. 12 arr3; .
10. 13, 14, 15, 16 arr3; .
10 ,
.
.10.28 , -
3.

,
.
2-3-4 ,
.
.
2-3-4 , -
.
2-3-4 : 2-
, 3- , 4-
.
2-3-4 1-.
2-3-4 .
, 0,
0; 1, 0
1; 2, 2.
2-3-4 -
, .
; -
.
483

2-3-4 .
2-3-4 - .
2-3-4 - 2-
, 3- -
, 4- -
.
3- /
.
2-3-4 --
.
-
() 3-.
2-3-4 log2N.
.
2-3-4 .
2-3 2-3-4,
, .
2-3, ,
,
.
-
( ).
, ,
.
, ,
.
,
.
( ).
B- ,
.
B- .
B

- -
, .
, ,

.
484 10. 2-3-4

.
.
1. 2-3-4 , :
a) ;
b) , ;
c) , ;
d) , .
2. 2-3-4
, ________ .
3. , 25, 50 75.
60 70, -
__________ .
4. (/).
5. ? :
a) ;
b) ;
c) ;
d)
.
6. 2-3-4 ________.
7. 2-3-4?
a) ;
b) ;
c) , ;
d) .
8. - 2-3-4. -
0, 1 2?
9. 4- 2-3-4 _______ - .
10. 2-3
( 2-3-4!) ?
a) ,
;
b) ;
c) 2 -
;
d) .
485

11. ( O-) 2-3?


12. , :
a) ,
;
b) -

;
c) ;
d) ,
.
13. B- _______ .
14. B- 2-3.
15.
, :
a) ;
b) ;
c) ;
d) .

.
.
1. 2-3-4
: 10, 20, 30, 40, 50, 60, 70, 80 90.
Tree234 Workshop.
2. 2-3
. 1.
3. , 2-3-4.


, -

. ( ,
.)
486 10. 2-3-4

10.1. , 2-3-4.
10.2. , 2-3-4. -
-
.
10.3. 2-3-4 .
sort(), main() -
.
10.4. tree234.java (. 10.1),
2-3 . -
. ,
, ()
. , split() .
insert(), , -
. , , . -
, ,
.
, .
10.5. . 10.4. split() ,
/ .
.
, split() -
, ,
.
11
-

- ,
. , :
( )
, : O(1) O-.
.
-
. ,
-
(, , ).
- , ,
,
O(logN). - , -
.
- . -
, .
- ,
,
( -
-
).
, - -
(, ).
, .
,
, -
.

- ,
-
. -
-. , ;
.
, -
, .
488 11. -


,
, 1000 .
1000. ,
.

.
1 () 1000 ( ).
;
. ,
(
..). ?


.
, .
.11.1.

. 11.1.

, -
. , Henry Alcazar, , -
72; , -
72. :
empRecord rec = databaseArray[72];
: -
.
1001.
:
databaseArray[totalEmployees++] = newRecord;

, -
.
489



.
, . -
,
.
, .
,
.

,
. .
, a zyzzyva (,
) , -
.
- -
.
, , -
. ,
-
.
,
50000 . ,
.
, ? ,
morphosis; ?


, .
,
. ASCII,
a 97, b 98 .., 122 z.

ASCII
- 0 255; -
, ..
26 , -
, . , a
1,
b
2 ..,
z
( 26). -
0, 27 . (
.)
, ?
. ,
.
490 11. -

-
. , cats .

:
c = 3
a = 1
t = 20
s = 19
:
3 + 1 + 20 + 19 = 43.
, cats -
43. ,
.
?
10 . a
(, 0):
0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 = 1.
zzzzzzzzzz
(10 z). ,
26 + 26 + 26 + 26 + 26 + 26 + 26 + 26 + 26 + 26 = 260.
, 1 260. ,
50000 , . -
192 (50000/260).
,
.
. ,
. ,
192 .
, .
. (,
was, tin, give, tend, moan, tick, bails, dredge 43,
cats.) ,
. -
.


. ,
(
a
zzzzzzzzzz

) -
?
491

,
.
, , ,
10 , . ,
7546
7*1000 + 5*100 + 4*10 + 6*1.
10:
7*103 + 5*102 + 4*101 + 6*100.
(
,
, , .)
, -
10 ( 10 ),
.
: ,
, -
27 ( 27 , )
.
.
, cats .
, ,
27 :
3*273 + 1*272 + 20*271 + 19*270.

3*19683 + 1*729 + 20*27 + 19*1,
, ,
59049 + 729 + 540 + 19 = 60 337.
-
. .
? , -
. 10- zzzzzzzzzz
26*279 + 26*278 + 26*277 + 26*276 + 26*275 + 26*274 + 26*273 +
+ 26*272 + 26*271 + 26*270.
279 7

000

000

000

000, -
. , ,
.
,
, ,
. ,
492 11. -

aaaaaaaaaa, aaaaaaaaab, aaaaaaaaac .., zzzzzzzzzz.


,
. . 11.2.



fira firb firc fird fire firf firg


125,146

125,147

125,148

125,149

125,150

125,151

125,152
. 11.2.

( ) -
. ( , 27)
.

, , -
- ,
.
, -
? 50000 , ,
. -
, (
). , 100000 .
, 0
7000000000000 0 100000.
(%).
, . , -
0 199 ( largeNumber)
0 9 ( smallNumber). -
10 ( smallRange).
(
). Java
:
smallNumber = largeNumber % smallRange;
10 0 9; -
, 13%10 3, 157%10 7 (.11.3).
0199 09, -
20:1.
493

,
, :
arrayIndex = hugeNumber % arraySize;
- ,
.
. , -
-, -. ( ,
-, .)
: , -
27.
hugeNumber = ch0*279 + ch1*278 + ch2*277 + ch3*276 + ch4*275 + ch5*274 +
+ch6*273 + ch7*272 + ch8*271 + ch9*270.

. 11.3.

(%) -
, -
. -:
arraySize = numberWords * 2;
arrayIndex = hugeNumber % arraySize;
494 11. -


( ),
( ). - -
. ,
.
, .
,
hugeNumber
long. , , .

. ,
.
,
. 260 (
10 ), 50000
.
,
( ). ,
, ,
. , ,
.
, melioration. ,
,
demystify, - (
). , . 11.4, .
, -
, .
,
. ,
.

( ,
-). . cats
5421, parsnip, -
cats , 5422.
( ) ,
.
. -
. ,
-.
.
, - .
495

- ,
. Workshop
, . ,
.
,
.

parchment

demystify melioration

slander

quixotic

. 11.4.


, -
-, .
,
: ,
.


.
, 5421 ,
5422, 5423 ..
, .
, -
.
496 11. -

Hash Workshop
Hash Workshop .
. 11.5 , .
0 999. -
60. -
. , ,
(%):
arrayIndex = key % arraySize;

. 11.5. Hash Workshop

60 :
arrayIndex = key % 60;
- , -
. 60 , ,
60. , - 143, 60 ( 83),
60 ( 23). ,
143. -
. ( 10
.)
,
. , -
, Find. ,
.
, Fill ,
Press any key.
. -
, Find , New
.
497

New
New - .
60; ,
. 60. ,
-,
, -
, 59 .

Fill
- 30 , -
. Fill
. Fill .
- ,
(40 60 ).
. -
,
.
-
. -
. ,
,
. 11.6.
, 24 144
(-
25
, 59 -
60) . 26
, 27 87
.
. 28 208

, - 29 989
- -
30 329
; ,
. 31 869

32 867
Find
33 29
Find -
, . 34

. - 35
, ,
36 336
-
. 37
,
. -
; -
. . 11.6.
498 11. -

.
.
Find
. ,
, , . -
, (
) . . 11.7
.

48 948 48 948
49 408 49 408
50 50
51 51
52 172 52 172

53 833 53 833

54 413 54 413
55 532 55 532
56 472 56 472
57 57
58 358 58 358


. 11.7. : 472;
893

Ins
Ins - , -
. ,
Find. , -
. , .
.
. -
, ,
.
. ,
,
4 5 -
.
,
. 60, 7, 67, 127, 187, 247 .. 967
499

7.
-
.

Del
Del , . -
. ? ,

. -
, ,
.

, .
, ,
1.
*Del*.
Ins
*Del*. Find *Del*
.
, - -
- *Del*, .
- . -
, .

- ?
Hash

Workshop

-
, Ins. ,
,
. , .
Find ,
, . -
. -
,
. ,
.

- Hash

Workshop

-
. .
.
,
.
500 11. -

, -
. , , ;
.
,
.
, -
, -
. ( -
.)

-
Java
, - -
.
Java, hash.java,
.

find()
find() hashFunc(),
hashVal. hashFunc() %
, .
while find() , -
(null). , , .
, find() ,
hashVal while, ,
.
find() :
public DataItem find(int key) //
// ( , )
{
int hashVal = hashFunc(key); //

while(hashArray[hashVal] != null) //
{ // ?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // ,
++hashVal; //
hashVal %= arraySize; //
} //
return null; //
}
, hashVal .
, .
501

if, hashVal
. -
% hashVal .
, -
, . ,
.
.

insert()
insert()
, ,
( 1).
, insert() .
public void insert(DataItem item) //
// ( , )
{
int key = item.getKey(); //
int hashVal = hashFunc(key); //
//
while(hashArray[hashVal] != null && // -1,
hashArray[hashVal].iData != -1)
{
++hashVal; //
hashVal %= arraySize; //
} //
hashArray[hashVal] = item; //
}

delete()
delete() , find(),
. , delete() -
nonItem 1.
public DataItem delete(int key) //
{
int hashVal = hashFunc(key); //

while(hashArray[hashVal] != null) //
{ // ?
if(hashArray[hashVal].getKey() == key)
{
DataItem temp = hashArray[hashVal]; //
hashArray[hashVal] = nonItem; //
return temp; //
}
++hashVal; //
502 11. -

hashVal %= arraySize; //
} //
return null; //
}

hash.java
11.1 hash.java.
DataItem, ,
int . , ,
(-
, employee partNumber).
HashTable hashArray .
nonItem, -
.

11.1. hash.java
// hash.java
// -
// : C:>java HashTableApp
import java.io.*;
////////////////////////////////////////////////////////////////
class DataItem
{ // ( )
private int iData; // ()
//--------------------------------------------------------------
public DataItem(int ii) //
{ iData = ii; }
//--------------------------------------------------------------
public int getKey()
{ return iData; }
//--------------------------------------------------------------
} // DataItem
////////////////////////////////////////////////////////////////
class HashTable
{
private DataItem[] hashArray; // -
private int arraySize;
// -------------------------------------------------------------
public HashTable(int size) //
{
arraySize = size;
hashArray = new DataItem[arraySize];
nonItem = new DataItem(-1); // -1
}
// -------------------------------------------------------------
public void displayTable()
{
System.out.print("Table: ");
503

for(int j=0; j<arraySize; j++)


{
if(hashArray[j] != null)
System.out.print(hashArray[j].getKey() + " ");
else
System.out.print("** ");
}
System.out.println("");
}
// -------------------------------------------------------------
public int hashFunc(int key)
{
return key % arraySize; // -
}
// -------------------------------------------------------------
public void insert(DataItem item) //
// ( , )
{
int key = item.getKey(); //
int hashVal = hashFunc(key); //
//
while(hashArray[hashVal] != null && // -1,
hashArray[hashVal].getKey() != -1)
{
++hashVal; //
hashVal %= arraySize; //
} //
hashArray[hashVal] = item; //
}
// -------------------------------------------------------------
public DataItem delete(int key) //
{
int hashVal = hashFunc(key); //

while(hashArray[hashVal] != null) //
//
{ // ?
if(hashArray[hashVal].getKey() == key)
{
DataItem temp = hashArray[hashVal]; //
hashArray[hashVal] = nonItem; //
return temp; //
}
++hashVal; //
hashVal %= arraySize; //
} //
return null; //
}
// -------------------------------------------------------------

504 11. -

11.1 ()
public DataItem find(int key) //
// ( , )
{
int hashVal = hashFunc(key); //

while(hashArray[hashVal] != null) //
//
{ // ?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // ,
++hashVal; //
hashVal %= arraySize; //
} //
return null; //
}
// -------------------------------------------------------------
} // HashTable
////////////////////////////////////////////////////////////////
class HashTableApp
{
public static void main(String[] args) throws IOException
{
DataItem aDataItem;
int aKey, size, n, keysPerCell;
//
System.out.print("Enter size of hash table: ");
size = getInt();
System.out.print("Enter initial number of items: ");
n = getInt();
keysPerCell = 10;
//
HashTable theHashTable = new HashTable(size);

for(int j=0; j<n; j++) //


{
aKey = (int)(java.lang.Math.random() *
keysPerCell * size);
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
}

while(true) //
{
System.out.print("Enter first letter of ");
System.out.print("show, insert, delete, or find: ");
char choice = getChar();
switch(choice)
{
case 's':
theHashTable.displayTable();
505

break;
case 'i':
System.out.print("Enter key value to insert: ");
aKey = getInt();
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
break;
case 'd':
System.out.print("Enter key value to delete: ");
aKey = getInt();
theHashTable.delete(aKey);
break;
case 'f':
System.out.print("Enter key value to find: ");
aKey = getInt();
aDataItem = theHashTable.find(aKey);
if(aDataItem != null)
{
System.out.println("Found " + aKey);
}
else
System.out.println("Could not find " + aKey);
break;
default:
System.out.print("Invalid entry\n");
}
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//--------------------------------------------------------------
} // HashTableApp
////////////////////////////////////////////////////////////////
506 11. -

main() HashTableApp -
- ( s), (i), -
(d) (f).
- -
. - , -
10000. (
.) s ,
; .
keysPerCell main()
. 10. ,
20 0 200.
, , -
20 , .
hash.java:
Enter size of hash table: 12
Enter initial number of items: 8

Enter first letter of show, insert, delete, or find: s


Table: 108 13 0 ** ** 113 5 66 ** 117 ** 47

Enter first letter of show, insert, delete, or find: f


Enter key value to find: 66
Found 66

Enter first letter of show, insert, delete, or find: i


Enter key value to insert: 100
Enter first letter of show, insert, delete, or find: s
Table: 108 13 0 ** 100 113 5 66 ** 117 ** 47

Enter first letter of show, insert, delete, or find: d


Enter key value to delete: 100
Enter first letter of show, insert, delete, or find: s
Table: 108 13 0 ** -1 113 5 66 ** 117 ** 47
0 119 (12*10 1). ** ,
. 100 4 ( -
0), 100%12 = 4. ,
100 1.


- ,
. Java
.
, (-
) .
, -
,
507

. , -
. ,
,
insert(). ,
.
. ,
,
, .
.
, -
( , -
, ).
, . getPrime()
, . ,
, isPrime().
private int getPrime(int min) // > min
{
for(int j = min+1; true; j++) // j > min
if( isPrime(j) ) // j ?
return j; // ,
}
// -------------------------------------------------------------
private boolean isPrime(int n) // n ?
{
for(int j=2; (j*j <= n); j++) // j
if( n % j == 0) // j ?
return false; // ,
return true; // ,
}
. , getPrime() -
2, ( , ).
,
.
Java Vector ,
, .
,
.


,
. . , -
, ,
. , . -
: ,
508 11. -

, , . ,
.

. 10000 , 6667 ,
2/3.
_ = _ / _;
-
. - -
, .
.
.
, ,
( , ).


, x,
x+1, x+2, x+3 ..
x+1, x+4, x+9, x+16, x+25 .. -
: x+12, x+22,
x+32, x+42, x+52 ..
. 11.8.

6 6
7 656 7 656
1
8 715 8 715
4 9 658 9 658
1
10 777 10 777
11 837 4 11 837
9
12 12
13 599 13 599
9
14 899 14 899
15 15 15 15
16 420 16 420
17 898 17 898
18 18


. 11.8. : 420;
481

, ,
- 59 New. -
509

, (Quad).
4/5 Fill (47
59 ). ,
, -
.
- ,
Cant complete fill -
.
. ,
;
, .
,
, Find , . -
.
,
, , . Find
;
, .

: , . , -
59 60. ( 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11,
7, 5, 3 2.) , -
.
, .


,
; .
, -
. , , ,
.
, 184, 302, 420 544 7
- . 302
, 420 4 , 544 9 .
, 7,
. .
.
, ,
.


, -
. - ,
510 11. -

, -
, : 1, 4, 9, 16 ..

( ).
, , -
.
-
.
, -
.
, - -
:
-.
0 (
, , -
).
,

= - ( % );
, . :
stepSize = 5 - (key % 5);
- HashDouble Workshop.
, ()
. -
1 5 (. 11.9).

0 472 0 472

1 178 1 178


2 769 2 769

2 3 5 3
4 236 4 236
2 5 62 5 62
6 537 6 537
2 7 7
8 539 8 539
2 9 5 9
10 887 10 887
11 11


. 11.9. : 887;
709
511

HashDouble
HashDouble Workshop , .
,
,
New Double,
.
, 9/10 .

-; -
.
. -
, ,
,
( 1 5).

Java
11.2 hashDouble.java, -
. hash.java (-
11.1), -: -
. ,
, , .

11.2. hashDouble.java
// hashDouble.java
// -
// : C:>java HashDoubleApp
import java.io.*;
////////////////////////////////////////////////////////////////
class DataItem
{ // ( )
private int iData; // ()
//--------------------------------------------------------------
public DataItem(int ii) //
{ iData = ii; }
//--------------------------------------------------------------
public int getKey()
{ return iData; }
//--------------------------------------------------------------
} // DataItem
////////////////////////////////////////////////////////////////
class HashTable
{
private DataItem[] hashArray; // -
private int arraySize;
private DataItem nonItem; //

512 11. -

11.2 ()
// -------------------------------------------------------------
HashTable(int size) //
{
arraySize = size;
hashArray = new DataItem[arraySize];
nonItem = new DataItem(-1);
}
// -------------------------------------------------------------
public void displayTable()
{
System.out.print("Table: ");
for(int j=0; j<arraySize; j++)
{
if(hashArray[j] != null)
System.out.print(hashArray[j].getKey()+ " ");
else
System.out.print("** ");
}
System.out.println("");
}
// -------------------------------------------------------------
public int hashFunc1(int key)
{
return key % arraySize;
}
// -------------------------------------------------------------
public int hashFunc2(int key)
{
// , ,
// - 1
// 5, 4, 3 2
return 5 - key % 5;
}
// -------------------------------------------------------------
//
public void insert(int key, DataItem item)
// ( , )
{
int hashVal = hashFunc1(key); //
int stepSize = hashFunc2(key); //
//
while(hashArray[hashVal] != null && // -1
hashArray[hashVal].getKey() != -1)
{
hashVal += stepSize; //
hashVal %= arraySize; //
}
hashArray[hashVal] = item; //
}
513

// -------------------------------------------------------------
public DataItem delete(int key) //
{
int hashVal = hashFunc1(key); //
int stepSize = hashFunc2(key); //

while(hashArray[hashVal] != null) //
{ // ?
if(hashArray[hashVal].getKey() == key)
{
DataItem temp = hashArray[hashVal]; //
hashArray[hashVal] = nonItem; //
return temp; //
}
hashVal += stepSize; //
hashVal %= arraySize; //
}
return null; //
}
// -------------------------------------------------------------
public DataItem find(int key) //
// ( , )
{
int hashVal = hashFunc1(key); //
int stepSize = hashFunc2(key); //

while(hashArray[hashVal] != null) //
{ // ?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // ,
hashVal += stepSize; //
hashVal %= arraySize; //
}
return null; //
}
// -------------------------------------------------------------
} // HashTable
////////////////////////////////////////////////////////////////
class HashDoubleApp
{
public static void main(String[] args) throws IOException
{
int aKey;
DataItem aDataItem;
int size, n;
//
System.out.print("Enter size of hash table: ");
size = getInt();
System.out.print("Enter initial number of items: ");

514 11. -

11.2 ()
n = getInt();
//
HashTable theHashTable = new HashTable(size);

for(int j=0; j<n; j++) //


{
aKey = (int)(java.lang.Math.random() * 2 * size);
aDataItem = new DataItem(aKey);
theHashTable.insert(aKey, aDataItem);
}

while(true) //
{
System.out.print("Enter first letter of ");
System.out.print("show, insert, delete, or find: ");
char choice = getChar();
switch(choice)
{
case 's':
theHashTable.displayTable();
break;
case 'i':
System.out.print("Enter key value to insert: ");
aKey = getInt();
aDataItem = new DataItem(aKey);
theHashTable.insert(aKey, aDataItem);
break;
case 'd':
System.out.print("Enter key value to delete: ");
aKey = getInt();
theHashTable.delete(aKey);
break;
case 'f':
System.out.print("Enter key value to find: ");
aKey = getInt();
aDataItem = theHashTable.find(aKey);
if(aDataItem != null)
System.out.println("Found " + aKey);
else
System.out.println("Could not find " + aKey);
break;
default:
System.out.print("Invalid entry\n");
}
}
}
//--------------------------------------------------------------
515

public static String getString() throws IOException


{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//--------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//--------------------------------------------------------------
} // HashDoubleApp
////////////////////////////////////////////////////////////////

hash.java. 11.1 , 21 -
23 .
1 5.

11.1. 23

-
1 1 1 4

2 38 15 2

3 37 14 3

4 16 16 4

5 20 20 5

6 3 3 2

7 11 11 4

8 24 1 1 2
9 5 5 5

10 16 16 4 20 1 5 9
11 10 10 5

516 11. -

11.1 ()
-
12 31 8 4

13 18 18 2

14 12 12 3

15 30 7 5

16 1 1 4

17 19 19 1

18 36 13 4 17
19 41 18 4 22
20 15 15 5 20 2 7 12 17 22 4
21 25 2 5 7 12 17 22 4 9 14 19 1 6

15 (10-
). -
. :
** 1 24 3 15 5 25 30 31 16 10 11 12 1 37 38 16 36 18 19 20 ** 41



. , ,
. , -
15 ( 0 14), 0
5. 0, 5, 10, 0, 5, 10
.. . ,
1, 2, 3 ..,
.
13 ( ), -
: 0, 5, 10, 2, 7, 12, 4, 9, 1, 6, 11,
3 .. ,
. ,
.
.
, -
, (
).

.
517


-
.
-.
,
. , ,
; -
. . 11.10.

6 906 881

7 807

8 458 383 333

9 559

10

11 611 536 461 161

12 712 637

13 563

. 11.10.

,
, . ,
, -
,
.

HashChain Workshop
HashChain Workshop
. -
(. 11.11).
,
. 25 (25 ).
; ,
. 6
. -, 100 , -
518 11. -

2,0.
6;
, . (
2,0.)

. 11.11. HashChain Workshop

HashChain,
Ins. ,
, .
HashChain ,
. (
hashChain.java.)
, Find.
, -
, .
5, , -
.
.


( -
)
. N
N ; , -
. ; ,
, ,
.
519

, -
,
.
O(1), , M
. , O(M),
.

Workshop
, - -
1 .
,
.
, 1/2
2/3, .
-
. ,
, -
.

Fill. -
; ,
, ,
. Find
.

,
. ,
. ,
. Del
Workshop .



, .
, -
(- , )
.
,
, .
-.
520 11. -

, , -
( ) -.
(buckets).
-
.
,
.
.

Java
hashChain.java SortedList Link.
,
. ( -
, ,
.) ; ,
,
;
. ,
.
- -
, , -
.
, .
hashChain.java ( 11.3) - -
, ( ).
, ,
. - ,
16 .

11.3. hashChain.java
// hashChain.java
// -
// : C:>java HashChainApp
import java.io.*;
////////////////////////////////////////////////////////////////
class Link
{ // ( )
private int iData; //
public Link next; //
// -------------------------------------------------------------
public Link(int it) //
{ iData= it; }
// -------------------------------------------------------------
521

public int getKey()


{ return iData; }
// -------------------------------------------------------------
public void displayLink() //
{ System.out.print(iData + " "); }
} // Link
////////////////////////////////////////////////////////////////
class SortedList
{
private Link first; //
// -------------------------------------------------------------
public void SortedList() //
{ first = null; }
// -------------------------------------------------------------
public void insert(Link theLink) //
{
int key = theLink.getKey();
Link previous = null; //
Link current = first;
//
while( current != null && key > current.getKey() )
{ // current <= key
previous = current;
current = current.next; //
}
if(previous==null) //
first = theLink; // first -->
else //
previous.next = theLink; // prev -->
theLink.next = current; // --> current
}
// -------------------------------------------------------------
public void delete(int key) //
{ // (, )
Link previous = null; //
Link current = first;
//
while( current != null && key != current.getKey() )
{ // key != current
previous = current;
current = current.next; //
}
//
if(previous==null) // ,
first = first.next; // first
else //
previous.next = current.next; //
} // end delete()
// -------------------------------------------------------------

522 11. -

11.3 ()
public Link find(int key) //
{
Link current = first; //
//
while(current != null && current.getKey() <= key)
{ // current,
if(current.getKey() == key) // ?
return current; //
current = current.next; //
}
return null; //
}
// -------------------------------------------------------------
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; //
while(current != null) //
{
current.displayLink(); //
current = current.next; //
}
System.out.println("");
}
} // SortedList
////////////////////////////////////////////////////////////////
class HashTable
{
private SortedList[] hashArray; //
private int arraySize;
// -------------------------------------------------------------
public HashTable(int size) //
{
arraySize = size;
hashArray = new SortedList[arraySize]; //
for(int j=0; j<arraySize; j++) //
hashArray[j] = new SortedList(); //
}
// -------------------------------------------------------------
public void displayTable()
{
for(int j=0; j<arraySize; j++) //
{
System.out.print(j + ". "); //
hashArray[j].displayList(); //
}
}
// -------------------------------------------------------------
523

public int hashFunc(int key) // -


{
return key % arraySize;
}
// -------------------------------------------------------------
public void insert(Link theLink) //
{
int key = theLink.getKey();
int hashVal = hashFunc(key); //
hashArray[hashVal].insert(theLink); // hashVal
}
// -------------------------------------------------------------
public void delete(int key) //
{
int hashVal = hashFunc(key); //
hashArray[hashVal].delete(key); //
}
// -------------------------------------------------------------
public Link find(int key) //
{
int hashVal = hashFunc(key); //
Link theLink = hashArray[hashVal].find(key); //
return theLink; //
}
// -------------------------------------------------------------
} // HashTable
////////////////////////////////////////////////////////////////
class HashChainApp
{
public static void main(String[] args) throws IOException
{
int aKey;
Link aDataItem;
int size, n, keysPerCell = 100;
//
System.out.print("Enter size of hash table: ");
size = getInt();
System.out.print("Enter initial number of items: ");
n = getInt();
//
HashTable theHashTable = new HashTable(size);

for(int j=0; j<n; j++) //


{
aKey = (int)(java.lang.Math.random() *
keysPerCell * size);
aDataItem = new Link(aKey);
theHashTable.insert(aDataItem);
}

524 11. -

11.3 ()
while(true) //
{
System.out.print("Enter first letter of ");
System.out.print("show, insert, delete, or find: ");
char choice = getChar();
switch(choice)
{
case 's':
theHashTable.displayTable();
break;
case 'i':
System.out.print("Enter key value to insert: ");
aKey = getInt();
aDataItem = new Link(aKey);
theHashTable.insert(aDataItem);
break;
case 'd':
System.out.print("Enter key value to delete: ");
aKey = getInt();
theHashTable.delete(aKey);
break;
case 'f':
System.out.print("Enter key value to find: ");
aKey = getInt();
aDataItem = theHashTable.find(aKey);
if(aDataItem != null)
System.out.println("Found " + aKey);
else
System.out.println("Could not find " + aKey);
break;
default:
System.out.print("Invalid entry\n");
}
}
}
//--------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
- 525

//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
}
//--------------------------------------------------------------
} // HashChainApp
////////////////////////////////////////////////////////////////
20 ,
20 s:
Enter size of hash table: 20
Enter initial number of items: 20
Enter first letter of show, insert, delete, or find: s
0. List (first-->last): 240 1160
1. List (first-->last):
2. List (first-->last):
3. List (first-->last): 143
4. List (first-->last): 1004
5. List (first-->last): 1485 1585
6. List (first-->last):
7. List (first-->last): 87 1407
8. List (first-->last):
9. List (first-->last): 309
10. List (first-->last): 490
11. List (first-->last):
12. List (first-->last): 872
13. List (first-->last): 1073
14. List (first-->last): 594 954
15. List (first-->last): 335
16. List (first-->last): 1216
17. List (first-->last): 1057 1357
18. List (first-->last): 938 1818
19. List (first-->last):
,
, . -
.

- (. ).

-
,
-, ,
.
526 11. -


- , -
. - . -
, . -
.
( Java C++ ,
2.)
-
,
-. , -
.


- -
. -
,
( ).
, -
.
-
. ,
. -
= % _;
. -
,
, , .


-
. ,
,
033-400-03-94-05-0-535
:
02: ( 1 999, 70).
35: (100, 150, 200, 250 .. 850).
67: ( 1 12).
89: ( 00 99).
1011: ( 1 99).
12: (0 1).
- 527

1315: (
100).
0334000394050535.
. -
0 9999999999999999 (,
70, , 50,
13 99). ,
. , -
.


, -
. , ,
0 15. ,
,
; ,
.
.


( , )
-. -
.
,
.
-
, int long. ,
, ,
.
: - .

.


- (%)
. ,
.
,
.
, ,
, .
. ,
528 11. -

50 , -
, 50. (, 53) ,
.
,
.


-
, .
, cats

= 3*273 + 1*272 + 20*271 + 19*270


,
.
:
index = (key) % arraySize;
Java :
public static int hashFunc1(String key)
{
int hashVal = 0;
int pow27 = 1; // 1, 27, 27*27 ..

for(int j=key.length()-1; j>=0; j--) //


{
int letter = key.charAt(j) - 96; //
hashVal += pow27 * letter; // 27
pow27 *= 27; // 27
}
return hashVal % arraySize;
}
. N ,
N1. letter -
, (a=1 ..)
27: N1, 27
N2 ..
hashFunc1() , .
, .
, ,
( , 17731827). ,

var4*n4 + var3*n3 + var2*n2 + var1*n1 + var0*n0

(((var4*n + var3)*n + var2)*n + var1)*n + var0
- 529


.
Java
-
:
public static int hashFunc2(String key)
{
int hashVal = key.charAt(0) - 96;
for(int j=1; j<key.length(); j++) //
{
int letter = key.charAt(j) - 96; //
hashVal = hashVal * 27 + letter; //
}
return hashVal % arraySize; //
}
, (
),
( ).
, hashFunc2() ,
. ,
hashVal int. ( long
).
, -
? : , ,
, .
, .
% .
,
, . (
.) hashFunc3():
public static int hashFunc3(String key)
{
int hashVal = 0;
for(int j=0; j<key.length(); j++) //
{
int letter = key.charAt(j) - 96; //
hashVal = (hashVal * 27 + letter) % arraySize; // %
}
return hashVal; // %
}
( ) .
, -
, 32 (
2) 27, -
>>, %.

, . ,
.
530 11. -

- -
. , -
.
. , 1000
.
, 9- -
. 1000,
9 . , 123-45-6789 -
123+456+789= 1368. % -
, 999.
1368%1000 = 368. 100, 9 -
:
12+34+56+78+9=189, 189%100 = 89.
10, . -
-,
. .


, -
O(1). -
-
. .
.
-
() ().
, , ( )
.
, -
.
-.
( , )
(
).
.

-.


-
,
.
531

-
, .
,
. ,
,
.


(P)
(L) .

P = (1 + 1/(1 L)2)/2.

P = (1 + 1/(1 L))/2.
(. , ), -
. . 11.12
.

. 11.12.
532 11. -

1/2 1,5 -
, 2,5 . 2/3
2,0 5,0,
.
, , 2/3,
1/2. , ,
. -

, -
, , .


-
,
.
( ) :
log2(1loadFactor)/loadFactor.
:
1/(1loadFactor).
. 11.13. -
0,5 , .
2/3 2,37 3,0 ,
0,8 2,90 5,0. ,
,
.


-
( ).
,
-, . ,
( )
,
. -
1+nComps, nComps .
, - arraySize , -
, N .
N/arraySize :
__ = N / arraySize
:
_ = N / arraySize
, .
533

. 11.13.

,
.
. ,
1 +_ / 2
,
. , , -
,
1 + _
. 11.14.

, -
.
1,0 (
).
,
, 2
.
534 11. -

. 11.14.

( ,
). - -
, 1.
, ,
,
1 + _/2.



-
. ,
, -
; ,
0,5
.
, -, -
, -
.
,
.
.
,
, , -
.
535


10, 2-3-4,
B
- -
, ( ).
-
.
10, ,
,
.

. , -
,
, .
-.


- -
. - .

, .
, ,
.


10: 8192 ,
512 . , 16 .
- . , -
100 . (-)
, 0 ( ) 99.
, -
. , 8 .
, .
800 . . 11.15.
, ,
. ,
, - -,
, .
, -
. -
:
, .
536 11. -

. 11.15.

-
-, , ,
.
8 .


- . -
,
-:
.
, ,
. -
,
.
;
, .
,
, . ,
, .
537

- -
. , ,
.

- .
.
- .
, -
, .
.
:
.
,
, .
.
, ,
.
:
, .
. ,
- x,
x, x+1, x+2, x+3 ..
, ,
.
- -
, .
.
x .
, x, x+1, x+4, x+9,
x+16 ..
,
( ) .
- , ,
, -
.
, , -
, .
538 11. -

,
-.
- s,
x, x+s, x+2s, x+3s, x+4s .. s ,
.

- .

0,5. -
2.
-
1,0, .
, -
.
1,0.

1,5, 2,0 .
-
.

,
(%) -
.
, %
( ).
- .
.
- -
. -,
.

.
.
1. ( O-) -
( )?
2. __________
.
539

3. :
a) ;
b) ;
c) x+1, x+2 .., ;
d) , .
4. -
_____________.
5. -
?
6. - , :
a) ;
b) ;
c) - -
;
d) - .
7. _____________ .
8. ________.
9. -
(/).
10. , :
a) ;
b) ;
c) ;
d) .
11. - , -
_____________.
12. ,
(/).
13. :
a) ;
b) ;
c) ;
d) .
14. , .
15. , -
, ___________.
540 11. -

.
.
1.
. Hash Workshop,
30 60 ( 0,5).
( ,
) 1. ,
,
, . ?
56 30/60 . -
0,6, 0,7, 0,8 0,9.
. 11.12?
2. HashDouble

Workshop

- -
, ,
, 24. , 16.
.
, ,
. - ,
-
. : .
3. HashChain 25 50 -
( 2,0). ,
.
, .
. (
. ?)


,

.
11.1. hash.java (. 11.1) , -
.
11.2. - , -
. -, ; .
. ,
, 26
.
11.3. -, (. -
).
541

. . -

, . , -
10?
11.4. rehash() hash.java. -
insert() -
, 0,5.
(.
). (
, 1).
11.5. -
. , -,
.
hashChain.java (. 11.3) Tree tree.java
(. 8.1 8). -
.
,
O(logN) O(N).
.
15 15 , 4.
, -.
, -
.
( : find() Tree ,
.) , ,
.
12

4, ,
,
( ) .

.
, .

, . (, -
, ..), . ,
, ,
, , ,
(, )
.

. 14, ,
( , -
).
(
ADT
) -
( ) , ,
.
ADT
, -
. 4
.
: -
, O(1), ,
O(N),
.
,
: (
heap
). -
O(logN). ,
, .

, , -
.
543


,
:
. (
). . 12.1
.
() . -
( ,
) 8, .
, ,
( ) .


. 12.1. : ;

. 12.2 , -
. ,
. : ,
.

. 12.2.
544 12.

, , ,
, , .
, 0 N1 ( . 12.2 N=13).
,
( ). , ,
. (,
, 4.)

, ADT
,
. ,
, ,
. :
class Heap
{
private Node heapArray[];

public void insert(Node nd)


{ }
public Node remove()
{ }
}
class priorityQueue
{
private Heap theHeap;

public void insert(Node nd)


{ theHeap.insert(nd); }
public Node remove()
{ return theHeap.remove() }
}
priorityQueue -
Heap; .
,
, ,
. -
,
.


,
, (-
). ,
.
545

, -
( ) , -
. , , -
. . 12.2,
, ,
( ),
. , , .
-
. -
. ,
-
,
. (
O(logN)), . (
,
O(N).)
, .

.
. ,
, -
Workshop.

. -
, .
0 :
maxNode = heapArray[0];
, ;
. .
, ,
.
:
1. .
2. .
3. , -
.

. . (
.12.2 12 5.)
:
heapArray[0] = heapArray[N-1];
N--;
546 12.

1.
, -
; ,
. 3
, .
.
2 ( ), 3
( ). -
. 12.3.

. 12.3.

. 12.3, (30) .
.12.3,, , ,
. ( ;
.) . 12.3,
.
,
, .
,
, . -
. 12.4.
547

. 12.4.

.
( ).
,
:
heapArray[N] = newNode;
N++;

. 12.5.
548 12.

,
. ,
,
. , ,
, .
. 12.5.
,
. ,
.
, -
.
. 12.4 12.5, , -
.

.


. 12.4 12.5 ,
.
,
. . 12.6, -
. A D,
B, C D .


. 12.6. : ;

;
. 12.6, .
,
.
. 12.6, ,
. A .
B A, C B, D C. ,
Heap Workshop 549

A D.
9 5.
A .
,
.
.
, , -
( ),
, . , . 12.6, A
A. ,
,
. B


A
A


B
-
, .
.

Heap Workshop
Heap

Workshop

, , -
:
. ,
.

Heap

Workshop
-
. 12.7.

. 12.7. Heap Workshop

Fill, Chng, Rem Ins , -


, . ,
.
550 12.

10 . Fill
1 31. -
Fill .


.
. , -
;
,
, .
, Chng. -
;
. .
, . -
.

Rem , -
. , , (
) . ,
, .

,
. -
.
Ins.

Java
heap.java .
,
, .
8,
. x :
(x1)/2;
2*x + 1;
2*x + 2.
. 12.2.
Java 551

/ -
.

trickleUp().
insert(), trickleUp(), :
public boolean insert(int key)
{
if(currentSize==maxSize) // ,
return false; //
Node newNode = new Node(key); //
heapArray[currentSize] = newNode; //
trickleUp(currentSize++); //
return true; //
}
, ,
, .
. , trickleUp() .
trickleUp() (. ) -
. , ,
bottom. while index
, . while -
, (index>0), (iData) index
.
while .
index ( ).
index ,
.
public void trickleUp(int index)
{
int parent = (index-1) / 2;
Node bottom = heapArray[index];
while( index > 0 &&
heapArray[parent].getKey() < bottom.getKey() )
{
heapArray[index] = heapArray[parent]; //
index = parent; // index
parent = (parent-1) / 2; // parent <-
}
heapArray[index] = bottom;
}
, bottom ,
, index. ,
, -
.
552 12.

, -
. ,
( currentSize-1) trickleDown() -
.
public Node remove() //
{ // (, )
Node root = heapArray[0]; //
heapArray[0] = heapArray[--currentSize]; // <-
trickleDown(0); //
return root; //
}
, - -
.
trickleDown() trickleUp(),
, . index
top. trickleDown()
remove(), index , ,
.
while , index
, . -
, (
), ,
largerChild .
, (
top) largerChild. ,
, .
public void trickleDown(int index)
{
int largerChild;
Node top = heapArray[index]; //
while(index < currentSize/2) //
{ //
int leftChild = 2*index+1;
int rightChild = leftChild+1;
//
if( rightChild < currentSize && // ( ?)
heapArray[leftChild].getKey() <
heapArray[rightChild].getKey() )
largerChild = rightChild;
else
largerChild = leftChild;
// top >= largerChild?
if(top.getKey() >= heapArray[largerChild].getKey())
Java 553

break;
//
heapArray[index] = heapArray[largerChild];
index = largerChild; //
}
heapArray[index] = top; // index <-
}
, top, -
, index.


trickleDown() trickleUp()
() ,
.
change():
public boolean change(int index, int newValue)
{
if(index<0 || index>=currentSize)
return false;
int oldValue = heapArray[index].getKey(); //
heapArray[index].setKey(newValue); //

if(oldValue < newValue) // ,


trickleUp(index); //
else // ,
trickleDown(index); //
return true;
}
, -
, iData
, .
, , .
, -
: . change()
, Heap Workshop
.
; ,
.

O(N).
(, -).
, -
.
554 12.


( )
Heap. ,
, ,
.

heap.java
heap.java ( 12.1) Node. -
iData, . -
, .
Heap , , isEmpty() displayHeap().
,
.

12.1. heap.java
// heap.java
//
// : C>java HeapApp
import java.io.*;
////////////////////////////////////////////////////////////////
class Node
{
private int iData; // ()
// -------------------------------------------------------------
public Node(int key) //
{ iData = key; }
// -------------------------------------------------------------
public int getKey()
{ return iData; }
// -------------------------------------------------------------
public void setKey(int id)
{ iData = id; }
// -------------------------------------------------------------
} // Node
////////////////////////////////////////////////////////////////
class Heap
{
private Node[] heapArray;
private int maxSize; //
private int currentSize; //
// -------------------------------------------------------------
public Heap(int mx) //
{
maxSize = mx;
currentSize = 0;
Java 555

heapArray = new Node[maxSize]; //


}
// -------------------------------------------------------------
public boolean isEmpty()
{ return currentSize==0; }
// -------------------------------------------------------------
public boolean insert(int key)
{
if(currentSize==maxSize)
return false;
Node newNode = new Node(key);
heapArray[currentSize] = newNode;
trickleUp(currentSize++);
return true;
}
// -------------------------------------------------------------
public void trickleUp(int index)
{
int parent = (index-1) / 2;
Node bottom = heapArray[index];
while( index > 0 &&
heapArray[parent].getKey() < bottom.getKey() )
{
heapArray[index] = heapArray[parent]; //
index = parent;
parent = (parent-1) / 2;
}
heapArray[index] = bottom;
}
// -------------------------------------------------------------
public Node remove() //
{ // (, )
Node root = heapArray[0];
heapArray[0] = heapArray[--currentSize];
trickleDown(0);
return root;
}
// -------------------------------------------------------------
public void trickleDown(int index)
{
int largerChild;
Node top = heapArray[index]; //
while(index < currentSize/2) //
{ //
int leftChild = 2*index+1;
int rightChild = leftChild+1;
//
if(rightChild < currentSize && // ( ?)
heapArray[leftChild].getKey() <

556 12.

12.1 ()
heapArray[rightChild].getKey())
largerChild = rightChild;
else
largerChild = leftChild;
// top >= largerChild?
if( top.getKey() >= heapArray[largerChild].getKey() )
break;
//
heapArray[index] = heapArray[largerChild];
index = largerChild; //
}
heapArray[index] = top; // index <-
}
// -------------------------------------------------------------
public boolean change(int index, int newValue)
{
if(index<0 || index>=currentSize)
return false;
int oldValue = heapArray[index].getKey(); //
heapArray[index].setKey(newValue); //

if(oldValue < newValue) // ,


trickleUp(index); // .
else // ,
trickleDown(index); // .
return true;
}
// -------------------------------------------------------------
public void displayHeap()
{
System.out.print("heapArray: "); //
for(int m=0; m<currentSize; m++)
if(heapArray[m] != null)
System.out.print( heapArray[m].getKey() + " ");
else
System.out.print( "-- ");
System.out.println();
//
int nBlanks = 32;
int itemsPerRow = 1;
int column = 0;
int j = 0; //
String dots = "...............................";
System.out.println(dots+dots); //

while(currentSize > 0) //
{
if(column == 0) // ?
for(int k=0; k<nBlanks; k++) //
Java 557

System.out.print(' ');
//
System.out.print(heapArray[j].getKey());
if(++j == currentSize) // ?
break;

if(++column==itemsPerRow) // ?
{
nBlanks /= 2; //
itemsPerRow *= 2; //
column = 0; //
System.out.println(); //
}
else //
for(int k=0; k<nBlanks*2-2; k++)
System.out.print( ); //
}
System.out.println("\n"+dots+dots); //
}
// -------------------------------------------------------------
} // Heap
////////////////////////////////////////////////////////////////
class HeapApp
{
public static void main(String[] args) throws IOException
{
int value, value2;
Heap theHeap = new Heap(31); //
boolean success; // 31

theHeap.insert(70); // 10 items
theHeap.insert(40);
theHeap.insert(50);
theHeap.insert(20);
theHeap.insert(60);
theHeap.insert(100);
theHeap.insert(80);
theHeap.insert(30);
theHeap.insert(10);
theHeap.insert(90);

while(true) // Ctrl+C
{
System.out.print("Enter first letter of ");
System.out.print("show, insert, remove, change: ");
int choice = getChar();
switch(choice)
{
case 's': //

558 12.

12.1 ()
theHeap.displayHeap();
break;
case 'i': //
System.out.print("Enter value to insert: ");
value = getInt();
success = theHeap.insert(value);
if( !success )
System.out.println("Cant insert; heap full");
break;
case 'r': //
if( !theHeap.isEmpty() )
theHeap.remove();
else
System.out.println("Cant remove; heap empty");
break;
case 'c': //
System.out.print("Enter current index of item: ");
value = getInt();
System.out.print("Enter new key: ");
value2 = getInt();
success = theHeap.change(value, value2);
if( !success )
System.out.println("Invalid index");
break;
default:
System.out.println("Invalid entry\n");
}
}
}
//-------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
return Integer.parseInt(s);
Java 559

}
//-------------------------------------------------------------
} // HeapApp
////////////////////////////////////////////////////////////////
0.
1, 0 -
. -
, .
main() HeapApp

-
31 ( ) 10
. , -
s, i, r c ( , , ).
:
Enter first letter of show, insert, remove, change: s
heapArray: 100 90 80 30 60 50 70 20 10 40
..............................................................
100
90 80
30 60 50 70
20 10 40
..............................................................
Enter first letter of show, insert, remove, change: i
Enter value to insert: 53
Enter first letter of show, insert, remove, change: s
heapArray: 100 90 80 30 60 50 70 20 10 40 53
..............................................................
100
90 80
30 60 50 70
20 10 40 53
..............................................................
Enter first letter of show, insert, remove, change: r
Enter first letter of show, insert, remove, change: s
heapArray: 90 60 80 30 53 50 70 20 10 40
..............................................................
90
60 80
30 53 50 70
20 10 40
..............................................................
Enter first letter of show, insert, remove, change:
, 53,
,
. show() :
, .
.
560 12.


,
?
. ( - -
.)
,
,
(, ).

Java Vector
.


- -

. :
.
:
,
. (
; -
.)
trickleUp() :
. trickle-
Down() :
.
.
,
8, L log2(N+1), N -
. trickleUp() trickleDown() L1
, log2N,
- . -
, , ,
O(logN).


,
.
.
. ,
561

, , , .
, ( ).
.

. ,
,
( ). -
, (
). ,
, .
,
.
8,
.
: 0
, 1 .
, , -
, . ,
1; 2 3; 4, 5, 6, 7 ..
. -
. ,
29 , . 29
11101 . ; 1101.
29: , , , .
30 1110 (
): , , , .
-
% 2 (0 1) -
n 2 /. n
, . ,
, . (
.) :
while(n >= 1)
{
path[j++] = n % 2;
n = n / 2;
}
:
,
.
( ) ,
.
, -
.

562 12.

. Node ,
. -
.
O(logN).
,
, .



,
.

insert(). remove() -
. :
for(j=0; j<size; j++)
theHeap.insert( anArray[j] ); //
for(j=0; j<size; j++)
anArray[j] = theHeap.remove(); //
insert() remove() O(logN),
N ,
O(N*logN) , . -
- ,
while trickleDown() ,
.
,
. , .


N , trickleUp() N .
, -
N/2 trickleDown().
.



, , , trickleDown() -
,

. ( ,
.) . 12.8.
563



-
, -
trickleDown()
A

. 12.8.

-
. trickleDown() () ,
, 0.
, trickleDown()
. trickleDown()
.
, ( )
, -
; , .
, trickleDown() .
N/21, , N1.
, N- insert()
. . 12.9
, 6 15 .

7.
0

6. 5.

1 2
4. 3. 2. 1.

3 4 5 6

7 8 9 10 11 12 13 14

. 12.9. trickleDown()
564 12.

trickleDown() ,
, N/21 :
for(j=size/2-1; j >=0; j--)
theHeap.trickleDown(j);


.
heapify() .
, ..
, -
, .
, heapify()
trickleDown() . , -
. heapify() ,
.
heapify(int index) //
{
if(index > N/2-1) // ,
return; //
heapify(index*2+2); //
heapify(index*2+1); //
trickleDown(index); //
}
, .


.
, -
.
N: , .

. , -
;
.
,
trickleDown() .
;
. , -
.
remove() .
?

; . -
565

.
, -
. ,

(. 12.10).

. 12.10.

heapSort.java
trickleDown() insert() -

. 12.2
heapSort.java.

12.2. heapSort.java
// heapSort.java
//
// : C>java HeapSortApp
import java.io.*;
////////////////////////////////////////////////////////////////
class Node
{
private int iData; // ()
// -------------------------------------------------------------
public Node(int key) //
{ iData = key; }
// -------------------------------------------------------------

566 12.

12.2 ()
public int getKey()
{ return iData; }
// -------------------------------------------------------------
} // Node
////////////////////////////////////////////////////////////////
class Heap
{
private Node[] heapArray;
private int maxSize; //
private int currentSize;
// -------------------------------------------------------------
public Heap(int mx)
{
maxSize = mx;
currentSize = 0;
heapArray = new Node[maxSize];
}
// -------------------------------------------------------------
public Node remove()
{
Node root = heapArray[0];
heapArray[0] = heapArray[--currentSize];
trickleDown(0);
return root;
}
// -------------------------------------------------------------
public void trickleDown(int index)
{
int largerChild;
Node top = heapArray[index]; //
while(index < currentSize/2) //
{
int leftChild = 2*index+1;
int rightChild = leftChild+1;
//
if(rightChild < currentSize && // ( ?)
heapArray[leftChild].getKey() <
heapArray[rightChild].getKey())
largerChild = rightChild;
else
largerChild = leftChild;
// top >= largerChild?
if(top.getKey() >= heapArray[largerChild].getKey())
break;
//
heapArray[index] = heapArray[largerChild];
index = largerChild; //
}
heapArray[index] = top; // index <-
}
567

// -------------------------------------------------------------
public void displayHeap()
{
int nBlanks = 32;
int itemsPerRow = 1;
int column = 0;
int j = 0; //
String dots = "...............................";
System.out.println(dots+dots); //

while(currentSize > 0) //
{
if(column == 0) // ?
for(int k=0; k<nBlanks; k++) //
System.out.print(' ');
//
System.out.print(heapArray[j].getKey());

if(++j == currentSize) // ?
break;

if(++column==itemsPerRow) // ?
{
nBlanks /= 2; //
itemsPerRow *= 2; //
column = 0; //
System.out.println(); //
}
else //
for(int k=0; k<nBlanks*2-2; k++)
System.out.print( ); //
}
System.out.println("\n"+dots+dots); //
}
// -------------------------------------------------------------
public void displayArray()
{
for(int j=0; j<maxSize; j++)
System.out.print(heapArray[j].getKey() + " ");
System.out.println("");
}
// -------------------------------------------------------------
public void insertAt(int index, Node newNode)
{ heapArray[index] = newNode; }
// -------------------------------------------------------------
public void incrementSize()
{ currentSize++; }
// -------------------------------------------------------------
} // Heap

568 12.

12.2 ()
////////////////////////////////////////////////////////////////
class HeapSortApp
{
public static void main(String[] args) throws IOException
{
int size, j;
System.out.print("Enter number of items: ");
size = getInt();
Heap theHeap = new Heap(size);

for(j=0; j<size; j++) //


{ //
int random = (int)(java.lang.Math.random()*100);
Node newNode = new Node(random);
theHeap.insertAt(j, newNode);
theHeap.incrementSize();
}

System.out.print("Random: ");
theHeap.displayArray(); //

for(j=size/2-1; j>=0; j--) //


theHeap.trickleDown(j);

System.out.print("Heap: ");
theHeap.displayArray(); //
theHeap.displayHeap(); //

for(j=size-1; j>=0; j--) //


{ //
Node biggestNode = theHeap.remove();
theHeap.insertAt(j, biggestNode);
}
System.out.print("Sorted: ");
theHeap.displayArray(); //
}
// -------------------------------------------------------------
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
//-------------------------------------------------------------
public static int getInt() throws IOException
{
String s = getString();
569

return Integer.parseInt(s);
}
// -------------------------------------------------------------
} // HeapSortApp
Heap heap.
java (. 12.1), ,
trickleUp() insert(), .
insertAt() .
, -
. Heap
. -
, insertAt() .
,
.
incrementSize(). -
, insertAt(),
,
.
main() HeapSortApp:
1) ;
2) ;
3) N/2 trickleDown();
4) .
. -
heapSort.java:
Enter number of items: 10
Random: 81 6 23 38 95 71 72 39 34 53
Heap: 95 81 72 39 53 71 23 38 34 6
..............................................................
95
81 72
39 53 71 23
38 34 6
..............................................................
Sorted: 6 23 34 38 39 53 71 72 81 95


,
O(N*logN). , -

.
O(N2),
O(N*logN) .
570 12.

(ADT)
( )
.
ADT.

O(N*logN).
.
, -
.
, -
. 0,
N1.
.
,
.
, , ,
.
-
, -
.
. -
. , ,
, .
( ),
; -
.

.
,
O(N*logN).
N
N .
,
N/2 (
N ).
,
. , -
.
571

.
.
1. ?
a) .
b) (, ).
c) .
d) .
2.
?
3. __________.
4. , :
a) ,
;
b) ,
;
c) ,
;
d) ,
.
5. , :
a) ;
b) ;
c) ;
d) .
6. :
a) ;
b) ;
c) ;
d) .
7. , _______
.
8. , ,
_____.
9. :
a) ;
b) ;
572 12.

c) ;
d) , .
10. ,
, ?

.
.
1. ? -
Heap Workshop .
2. Workshop 10 , ,
( Ins).
Rem, ?
3. , .
,
? .


,

.
12.1. heap.java (. 12.1),
, ( -
, .) ,
.
12.2. heap.java insert()
. toss(),
. (, -
.)
restoreHeap(), .
toss()
restoreHeap() , insert().
, ,
toss() .
12.3. PriorityQ priorityQ.java (. 4.6)
( ). Heap -
heap.java (. 12.1) - .
( ).
573

12.4. -
, , .
, ,
- 11.4 11, -.
,
( ). -
( ).
Tree tree.java (. 8.1).
,
removeMax(). -
, .
? ?
change()
.
PriorityQ; Tree
main() ( -
). removeMax() O(logN).
12.5. , (
), . -
, .
13

, -
. , , ,
, .
, , ,

.
. -
,
, ,
Workshop

. -
, .


. , -
. -
, .
, , -
. , , -
.
.
,
. , ,
. , : -
, ,
. ,
.
.
, ,
. , ,

.
. -
.
575

. 13.1, -
( ). . 13.1, ,
.
, , -
, . ,
. -
, .
, .
;
,
. -
. ,
, , I H, 101, 84
280. ( ),
.

, . ,
. 13.1 I G , I F . ,
, . , G
I, H F.

. . 13.1

B

J
, A


E
; -
BAEJ. ;
, B J BCDJ.


, -
(. 13.2, ). (
, ),
. 13.2, .
. . 13.2,
A B, C D.
, ,
. ,

.
576 13.

. 13.1. () ()

B B

A D A D

C C


. 13.2. () ()


. 13.1 13.2 . ,
; -
, A B,
577

B A.
, .
, -
A B,
B A, .
( ). -
.
,
,
(, ).
, , .
, ;
.
,
. -
.


, ,
(
XVIII
). , -
(. 13.3,
). ,
.
; , . ,
.
, (. 13.3, ). ,
.


. 13.3. : ;
578 13.


-
.
.
? , .

-
0 N1 ( N ). -
, .

, . , -
, -
, , .. ,

. -
(, A) , (
). Vertex :
class Vertex
{
public char label; // (, A)
public boolean wasVisited;

public Vertex(char lab) //


{
label = lab;
wasVisited = false;
}
} // Vertex
. -
vertexList.
. ,
.
.
.

9, - , -
.
, ,
,
. 12, ,
-
.
579

, . -
,
. ,
.13.2,
A
, C

-
.

. :
. (,
, .)


,
. N ,
NN. 13.1
. 13.2, .

13.1.
A B C D
A 0 1 1 1
B 1 0 0 1
C 1 0 0 0
D 1 1 0 0

, .
1; 0.
( true/false.)
, A

, -
B A D, C A, D A B.
0, ,
( AA DD),
. , -
1, .
:
, ;
. ,

, .

.



( , 5). ,
580 13.

( ).
,
. 13.2
. 13.2, .

13.2.

A B>C>D
B A>D
C A
D A>B

> .
. -
, .
. , -
(
); .
, -
, .
Workshop ,
.


, -
new vertexList.
,
. ,
:
vertexList[nVerts++] = new Vertex('F');
F. nVerts
. -
( ). ,
, 1
3. vertexList,
. adjMat .
, :
adjMat[1][3] = 1;
adjMat[3][1] = 1;
3 1, -
1 3.
581

Graph
Graph ,
Graph:
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
// -------------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = 0;
}
// -------------------------------------------------------------
public void addVertex(char lab) //
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
} // Graph
Graph vertexList.
.
.
, ( ), -
, ,
.
,
. .
582 13.

, ,
, . ,
,
- ( ). .
, .
, - ,
-
.
, ,
. ,
, . -
,
. ,

, -
(. 13.4).

. 13.4.

, .
,
, . ,

, .
, . , -

, ,
. 8, ,
, .
583

:
.
. ,
. ,
.


, -
. , -
GraphN Workshop,
.

. 13.5.
.

A. : ,
-
3 4
. 2 B F H
,
5
A, . , C
; , 1 A
B

. B

, - 6 7 8
D G I
.
? B

, - E
, : 9
, . . 13.5.
F.
1.
1
, , .

1 H

. -
- ,
, H. 2.
2
1 , .

H ,
F

. F

-
584 13.

; . B.
A. A
, C.
, , -
A. D, G I,
I

.
A
. E

-
A.
A

, -
. , 3.
3
1 2 , .

13.3 -
. 13.5.

13.3.

A A
B AB
F ABF
H ABFH
H ABF
F AB
B A
AC
A
D AD
G ADG
I ADGI
I ADG
G AD
D A
E AE
E A
A

. -
, ,
585

.
ABFHCDGIE.
, -
.
, -
, .

.
() (),
.
, . , ,
. ,
.
, .
-
.., . , ,
. ,
, .
,
, .
: .

GraphN Workshop
DFS GraphN Workshop
.
. ,
.
.
A

,
B
.. -
. , .
. 13.6 . 13.5, .
,
, New
( ). View
(. 13.7).
View .
DFS.
( !) , .
. 13.6
.
, (
).
586 13.

. 13.6. GraphN Workshop

. 13.7. GraphN Workshop

, -
.

Java
,
. ?
.
, 1; -
. , .
587

, , .
1 (),
, , ,
, .
getAdjUnvisitedVertex():
// , v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j; //
return -1; //
}
dfs() Graph, -
. ,
. , .
:
1) peek();
2) ;
3) , ;
4) , .
dfs():
public void dfs() //
{ // 0
vertexList[0].wasVisited = true; //
displayVertex(0); //
theStack.push(0); //

while( !theStack.isEmpty() ) //
{
// ,
int v = getAdjUnvisitedVertex( theStack.peek() );
if(v == -1) // ,
theStack.pop(); //
else //
{
vertexList[v].wasVisited = true; //
displayVertex(v); //
theStack.push(v); //
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
588 13.

dfs() wasVisited, dfs()


. .
Graph.
, ,
:
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4

theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD B C
theGraph.addEdge(3, 4); // DE

System.out.print("Visits: ");
theGraph.dfs(); //
A
System.out.println();
, ,
. 13.8. :
Visits: ABCDE
D E
,
; - . 13.8. ,
, . dfs.java bfs.java

dfs.java
13.1 dfs.java dfs(). -
StackX 4, .
13.1. dfs.java
// dfs.java
//
// : C>java DFSApp
////////////////////////////////////////////////////////////////
class StackX
{
private final int SIZE = 20;
private int[] st;
private int top;
// -----------------------------------------------------------
public StackX() //
{
st = new int[SIZE]; //
top = -1;
}
589

// -----------------------------------------------------------
public void push(int j) //
{ st[++top] = j; }
// -----------------------------------------------------------
public int pop() //
{ return st[top--]; }
// ------------------------------------------------------------
public int peek() //
{ return st[top]; }
// ------------------------------------------------------------
public boolean isEmpty() // true,
{ return (top == -1); }
// ------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
public boolean wasVisited;
// ------------------------------------------------------------
public Vertex(char lab) //
{
label = lab;
wasVisited = false;
}
// ------------------------------------------------------------
} // Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
private StackX theStack;
// -----------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = 0;
theStack = new StackX();
}
// -----------------------------------------------------------

590 13.

13.1 ()
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -----------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// ------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// ------------------------------------------------------------
public void dfs() //
{ // 0
vertexList[0].wasVisited = true; //
displayVertex(0); //
theStack.push(0); //

while( !theStack.isEmpty() ) //
{
// ,
int v = getAdjUnvisitedVertex( theStack.peek() );
if(v == -1) // ,
theStack.pop(); //
else //
{
vertexList[v].wasVisited = true; //
displayVertex(v); //
theStack.push(v); //
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
// ------------------------------------------------------------
// , v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j; //
return -1; //
}
591

// ------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class DFSApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4

theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE

System.out.print("Visits: ");
theGraph.dfs(); //
System.out.println();
}
} // DFSApp
////////////////////////////////////////////////////////////////


( -
).
. ,
.. .
, ,
.
-.
9 . 8 . .
,
.., .
? ,
, ..
,
. -
, . -
.
, .
, ;
, ..
592 13.

.
, ,
.
.
, ,
9*8*7*6*5*4*3*2*1 . 9! ( 9), 362880.
, , ,
(, Deep Blue IBM)
. ,
, -
.
-
. ,
, getAdjUnvisitedVertex() dfs.java (. 13.1).
( ),
. -
(getAdjUnvisitedVertex() 1), -
, , ,
.
,
. . -
- ,
, .
, ,
. 9!
. .
-
, .
, -
, (,
).
.
. -
. ,
.
.


,
. -
, , .
, ,
. ( ).
593

. 13.9 , . 13.5,
. , .

2 6 8
B F H
3
C
1
A

4 7 9
D G I
5
E

. 13.9.

A; .
.
1
, , ,
.

2
1 , -
.

3
1 2 , .

, , A.
. A,
B, C, D E. ( ) BCDE.

A
, -
B , B. F
. , B, ,
C .
,
D

G
.
D
-
, E.
FG. F H, G
I.
HI

. -
, ,
. 13.4
.
594 13.

13.4.

A

B B
C BC
D BCD
E BCDE
B CDE
F CDEF
C DEF
D EF
G EFG
E FG
F G
H GH
G H
I HI
H I
I

,
, .
( ,
.) ABCDEFGHI.

GraphN Workshop
GraphN Workshop
( BFS). , . 13.9
.

.
, -
, , ,
.
, , ,
. .
595

Java
bfs() Graph dfs(), ,
.
, -
. :
public void bfs() //
{ // 0
vertexList[0].wasVisited = true; //
displayVertex(0); //
theQueue.insert(0); //
int v2;

while( !theQueue.isEmpty() ) //
{
int v1 = theQueue.remove(); //
//
while( (v2=getAdjUnvisitedVertex(v1)) != -1 )
{ //
vertexList[v2].wasVisited = true; //
displayVertex(v2); //
theQueue.insert(v2); //
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
, dfs.java (. . 13.8),
bfs.java :
Visits: ABDCE

bfs.java
bfs.java, 13.2, dfs.java;
: StackX Queue ( -
4), dfs() bfs().

13.2. bfs.java
// bfs.java
//
// : C>java BFSApp
////////////////////////////////////////////////////////////////
class Queue
{
private final int SIZE = 20;

596 13.

13.2 ()
private int[] queArray;
private int front;
private int rear;
// -------------------------------------------------------------
public Queue() //
{
queArray = new int[SIZE];
front = 0;
rear = -1;
}
// -------------------------------------------------------------
public void insert(int j) //
{
if(rear == SIZE-1)
rear = -1;
queArray[++rear] = j;
}
// -------------------------------------------------------------
public int remove() //
{
int temp = queArray[front++];
if(front == SIZE)
front = 0;
return temp;
}
// -------------------------------------------------------------
public boolean isEmpty() // true,
{
return ( rear+1==front || (front+SIZE-1==rear) );
}
// -------------------------------------------------------------
} // Queue
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) //
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
597

private Vertex vertexList[]; //


private int adjMat[][]; //
private int nVerts; //
private Queue theQueue;
// ------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = 0;
theQueue = new Queue();
}
// -------------------------------------------------------------
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
public void bfs() //
{ // 0
vertexList[0].wasVisited = true; //
displayVertex(0); //
theQueue.insert(0); //
int v2;

while( !theQueue.isEmpty() ) //
{
int v1 = theQueue.remove(); //
//

while( (v2=getAdjUnvisitedVertex(v1)) != -1 )
{ //
vertexList[v2].wasVisited = true; //
displayVertex(v2); //

598 13.

13.2 ()
theQueue.insert(v2); //
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
// -------------------------------------------------------------
// , v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j; //
return -1; //
}
// -------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class BFSApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE

System.out.print("Visits: ");
theGraph.bfs(); //
System.out.println();
}
}
////////////////////////////////////////////////////////////////
:
, ,
..
.
, , -
.
, .
599


, (
.13.4), . ,
,
.
,
( )
. -
, . ,
. 13.10, , . 13.10,
,
. (
MST
,
Mini-
mum Spanning Tree).

A A

B C B C

D E D E

. 13.10. : ;


. . 13.10,
AB
,
BC
,
CD
DE

, -

AC, CE, ED DB. ,
E
V:
E = V 1.
, .
, . (
, .)
-
. ,
. .
, ,
,
. -
mst() , ,
dfs(), , , mst()
- .
600 13.

GraphN Workshop
Tree GraphN


Workshop
-
. . ,
, ( DFS). -
Tree ,
, .
, .
Tree ,
.


Java
mst() :
while( !theStack.isEmpty() ) //
{ //
int currentVertex = theStack.peek();
// get next unvisited neighbor
int v = getAdjUnvisitedVertex(currentVertex);
if(v == -1) // ,
theStack.pop(); //
else //
{
vertexList[v].wasVisited = true; //
theStack.push(v); //
//
displayVertex(currentVertex); // currentVertex
displayVertex(v); // v
System.out.print(" ");
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
, dfs(). else -
.
, .
.
main() mst.java :
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
601

theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4

theGraph.addEdge(0, 1); // AB
theGraph.addEdge(0, 2); // AC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(0, 4); // AE
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(1, 3); // BD
theGraph.addEdge(1, 4); // BE
theGraph.addEdge(2, 3); // CD
theGraph.addEdge(2, 4); // CE
theGraph.addEdge(3, 4); // DE
. 13.10, . mst()
, , . 13.10, . -
mst.java :
Minimum spanning tree: AB BC CD DE
,
, . -
, , .
,
getAdjUnvisitedVertex() , vertexList[].

, , .
, , -
. ,
.

mst.java
13.3 mst.java. dfs.
java mst() main().

13.3. mst.java
// mst.java
//
// : C>java MSTApp
////////////////////////////////////////////////////////////////
class StackX
{
private final int SIZE = 20;
private int[] st;
private int top;
// -------------------------------------------------------------
public StackX() //
{

602 13.

13.3 ()
st = new int[SIZE]; //
top = -1;
}
// -------------------------------------------------------------
public void push(int j) //
{ st[++top] = j; }
// -------------------------------------------------------------
public int pop() //
{ return st[top--]; }
// -------------------------------------------------------------
public int peek() //
{ return st[top]; }
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return (top == -1); }
// -------------------------------------------------------------
} // StackX
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
public boolean wasVisited;
// -------------------------------------------------------------
public Vertex(char lab) //
{
label = lab;
wasVisited = false;
}
// -------------------------------------------------------------
} // Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
private StackX theStack;
// -------------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = 0;
603

theStack = new StackX();


}
// -------------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
public void mst() //
{ //
vertexList[0].wasVisited = true; //
theStack.push(0); //
while( !theStack.isEmpty() ) //
{ //
int currentVertex = theStack.peek();
//
int v = getAdjUnvisitedVertex(currentVertex);
if(v == -1) // ,
theStack.pop(); //
else //
{
vertexList[v].wasVisited = true; //
theStack.push(v); //
//
displayVertex(currentVertex); // currentVertex
displayVertex(v); // v
System.out.print(" ");
}
}

// ,
for(int j=0; j<nVerts; j++) //
vertexList[j].wasVisited = false;
}
// -------------------------------------------------------------
// , v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j;
return -1;
}

604 13.

13.3 ()
// -------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class MSTApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(0, 2); // AC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(0, 4); // AE
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(1, 3); // BD
theGraph.addEdge(1, 4); // BE
theGraph.addEdge(2, 3); // CD
theGraph.addEdge(2, 4); // CE
theGraph.addEdge(3, 4); // DE

System.out.print("Minimum spanning tree: ");


theGraph.mst(); //
System.out.println();
}
} // MSTApp
////////////////////////////////////////////////////////////////
, main(), , -
.
:
Minimum spanning tree: AB BC CD DE



,
. ,
.
.
605


. -
. ,

. . 13.11 () ,
.

. 13.11.

, (-
) -
.
,
. ,
,
.


. 13.11,
. ,
: .
.

A
.
.
-
B C
,
. 13.12.
. . 13.12
606 13.

, . 13.5
.

13.5.
A B C

A 0 1 0
B 0 0 1
C 0 0 0

1.
, . ,
A B 1 A
B. , B
A, B A.
, , -
,
. -
. .

:
public void addEdge(int start, int end) //
{
adjMat[start][end] = 1;
}
, .
, -
A B, ( ) B
A .


, ,
, . 13.11. -
. ,
:
BAEDGCFH
, ,
. ,
, .
, ,
. , -
C F:
CFBAEDGH
607

.
. , -
,
.

, . ,
,
. -
,
.

. (.
) , -
. ,
, .

GraphD Workshop
GraphD Workshop .
,
GraphN
, , -
. :
, .
. 13.13 GraphD


Workshop
, -
. 13.11.

. 13.13. GraphD Workshop

,
. .
608 13.

1
, .

, -
, , .
, A B, B A.
.13.11 , H.

2
.

1 2 , -
. , -
.
, , GraphD.
. 13.11 ( ); -
, .
Topo.
.
,
.
, .
( ) -
,
GraphD.
, , ,
.
, ; -
..
, -
.
,
.


, -
, . ? ,
, . . 13.14
B-C-D-B . ( : A-B-C-A ,
C A .)
, B
C, C D, D
B.
609

, , . - B
,
, . -
A D
, -
.
C
( ,
). . 13.14.

-
. N N1
, . ,
N N , .
,
.
.

Java
topo(), ,
Java :
public void topo() //
{
int orig_nVerts = nVerts; //

while(nVerts > 0) //
{
// -1
int currentVertex = noSuccessors();
if(currentVertex == -1) //
{
System.out.println("ERROR: Graph has cycles");
return;
}
// ( )
sortedArray[nVerts-1] = vertexList[currentVertex].label;

deleteVertex(currentVertex); //
}
// , sortedArray
System.out.print("Topologically sorted order: ");
for(int j=0; j<orig_nVerts; j++)
System.out.print( sortedArray[j] );
System.out.println("");
}
610 13.

while,
, 0.
:
1. noSuccessors() , .
2. , sortedArray[],
.
3. , , .
,
sortedArray, ,
nVerts ( ).
, , ,
, . -
while, sortedArray
.
noSuccessors() ,
. for ,
. for -
1. , ,
( ,
). 1 -
.
, 1, ,
;
. , 1. noSuccessors():
public int noSuccessors() // ,
{ // ( -1, )
boolean isEdge; // adjMat, row column

for(int row=0; row<nVerts; row++) //


{
isEdge = false; //
for(int col=0; col<nVerts; col++)
{
if( adjMat[row][col] > 0 ) //
{ //
isEdge = true;
break; //
} //
} //
if( !isEdge ) // ,
return row; //
}
return -1; //
}
, .
vertexList[],
611

, . -
,
. -
deleteVertex(), moveRowUp() moveColLeft(),
topo.java ( 13.4). ,

, .
main() . 13.10 , ,
. addEdge(), ,
, .
main():
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex(A); // 0
theGraph.addVertex(B); // 1
theGraph.addVertex(C); // 2
theGraph.addVertex(D); // 3
theGraph.addVertex(E); // 4
theGraph.addVertex(F); // 5
theGraph.addVertex(G); // 6
theGraph.addVertex(H); // 7
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(0, 4); // AE
theGraph.addEdge(1, 4); // BE
theGraph.addEdge(2, 5); // CF
theGraph.addEdge(3, 6); // DG
theGraph.addEdge(4, 6); // EG
theGraph.addEdge(5, 7); // FH
theGraph.addEdge(6, 7); // GH
theGraph.topo(); //
}
, main() topo() -
. :
Topologically sorted order: BAEDGCFH
, main() , .

topo.java
topo.java. 13.4
.

13.4. topo.java
// topo.java
//
// : C>java TopoApp

612 13.

13.4 ()
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
// -------------------------------------------------------------
public Vertex(char lab) //
{ label = lab; }
} Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
private char sortedArray[];
// -------------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = 0;
sortedArray = new char[MAX_VERTS]; //
}
// -------------------------------------------------------------
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
public void topo() //
{
int orig_nVerts = nVerts; //

while(nVerts > 0) //
613

{
// -1
int currentVertex = noSuccessors();
if(currentVertex == -1) //
{
System.out.println("ERROR: Graph has cycles");
return;
}
// ( )
sortedArray[nVerts-1] = vertexList[currentVertex].label;

deleteVertex(currentVertex); //
}

// , sortedArray
System.out.print("Topologically sorted order: ");
for(int j=0; j<orig_nVerts; j++)
System.out.print( sortedArray[j] );
System.out.println("");
}
// -------------------------------------------------------------
public int noSuccessors() // ,
{ // ( -1, )
boolean isEdge; // adjMat, row column

for(int row=0; row<nVerts; row++) //


{
isEdge = false; //
for(int col=0; col<nVerts; col++)
{
if( adjMat[row][col] > 0 ) //
{ //
isEdge = true;
break; //
} //
} //
if( !isEdge ) // ,
return row; //
}
return -1; //
}
// -------------------------------------------------------------
public void deleteVertex(int delVert)
{
if(delVert != nVerts-1) //
{ // vertexList
for(int j=delVert; j<nVerts-1; j++)
vertexList[j] = vertexList[j+1];
// adjMat
for(int row=delVert; row<nVerts-1; row++)

614 13.

13.4 ()
moveRowUp(row, nVerts);
// adjMat
for(int col=delVert; col<nVerts-1; col++)
moveColLeft(col, nVerts-1);
}
nVerts--; // 1
}
// -------------------------------------------------------------
private void moveRowUp(int row, int length)
{
for(int col=0; col<length; col++)
adjMat[row][col] = adjMat[row+1][col];
}
// -------------------------------------------------------------
private void moveColLeft(int col, int length)
{
for(int row=0; row<length; row++)
adjMat[row][col] = adjMat[row][col+1];
}
// -------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class TopoApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addVertex('F'); // 5
theGraph.addVertex('G'); // 6
theGraph.addVertex('H'); // 7
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(0, 4); // AE
theGraph.addEdge(1, 4); // BE
theGraph.addEdge(2, 5); // CF
theGraph.addEdge(3, 6); // DG
theGraph.addEdge(4, 6); // EG
theGraph.addEdge(5, 7); // FH
theGraph.addEdge(6, 7); // GH
theGraph.topo(); //
}
} // TopoApp
////////////////////////////////////////////////////////////////
,
, .
615


,
( ).
.
,
.
. 13.15.
A
, -
C, . B,
D, C
. , ,
: , ?


dfs.java (. 13.1) -
,
.
. 13.15:
AC
BACE
C
DEC
EC
-
. . 13.15.

, ,
( )
.


,
. , ,
.
?
,
O(N) ( N ,
). ;
?
, , (
O(1)) , .
.
, ,
.
616 13.

,
, . ( .)
C D ,
, C D.
. (, -
, D C.) 13.6
. 13.15.

13.6.
A B C D E

A 0 0 1 0 0
B 1 0 0 0 1
C 0 0 0 0 0
D 0 0 0 0 1
E 0 0 1 0 0

-
. ,
, :

L
M

,
M
-
N, L N.
.
, -
.
? ,
. -
, -
.
, .
, . 13.6. -
, .

A

A
.
A

B
, C

1; -
.
, A C.
, X A,
X C.
A ( ?)?
A. . 13.6 , A
B. , B A.
617

, B A () A C.
, B C . .
13.15. , 1 B
C (. 13.16, ).
A .

B, C D
B. ( A) 1,
B A. ,
B? B ; , B
, -
B.

. 13.16. : ) y = 0; ) y = 4


C
, D

. -
D E. D ; ,
D, .

E
E E C. E,
B E; B E E C
B C. ,
1 . D E E C D C,
1. . 13.16, .
.
; ,
.
,
. 13.15.
618 13.



( . ).
( y).
( x). (x,y) 1, ,
y x; () z.
y ,
y. ( : y
, .)
y z 1, , z y. -
z y y x
z x, 1 (x, z).
.

, .
:
, , ..
-
. .
.
,
.
, -
.

.
(
).
,
, A B A B
.
-
.

, ,
.
( -
) .
619

.
.
1. _______ _________ .
2.
?
3. -
?
4. , :
a) ;
b) A B, C
..;
c) ;
d) -
.
5. {0,1,0,0}, {1,0,1,1}, {0,1,0,0} {0,1,0,0}.
?
6. , :
a) , , ;
b) ;
c) ;
d) .
7. -
?
8. , :
a) ;
b) ;
c) ;
d) .
9. , , ______.
10.
?
11.
(/).
12. :
a) ,
;
b) ;
620 13.

c) , A B, B C
..;
d) , , -
, .
13. ?
14. topo.java (. 13.4)
?

.
.
1. GraphN Workshop
. , View.
View .
2. - 3 3;
2 2,
. GraphN
, 2 2.
4?
3. , 0
1. .
View GraphD
Workshop. View , -
.
4. GraphD Workshop ,
topo().


,

.
13.1. bfs.java (. 13.2) , -

mst.java (. 13.3). main()
9 12 , .
13.2. dfs.java (. 13.1),
.
621

Link LinkList linkList2.java (.


5.2) 5. find() LinkList, -
.
13.3. dfs.java (. 13.1), -
(.
).
13.4.
. 13.3. -
.
13.5. . -
,
. ,
. ,
.
8 8 ,
5 5 .
. ,
, .
,
. ,
( ).
, 1 64
( 1 25 5 5).
,
( ) .
,
: ,

. .
14

, .
: . ,
,
,
( -
).
-
.
? ( ) -
?
.
,
. ,
, -
,
.



,
.
, . -
, ( 13,
) ,
. ,
.

:
, , -
.
, ?
623

,
.
. 14.1 , -
. . ,
. :
- -
. , A C D E ,
, .
10
B C
6 6
7

A 7 5 F
8

4 12 7
D E

. 14.1.

-
? .
( ),
, .
. 14.1? ,
GraphW Workshop.

GraphW Workshop
GraphW

Workshop

GraphN


GraphD
, -
.
, .
: Tree -
. New View, -
,
.
,
. ( -
, .)
,
, , . , -
, .
. , AB6
A B 6.
.
GraphW Workshop . 14.1.
. 14.2.
624 14.

. 14.2. GraphW Workshop

, -
( Tree). ,
. 14.3.

B C
6 6
7

A 5 F

4
D E

. 14.3.

,
AD, AB, BE, EC CF 28.
. , ,
.


,
.
(, , ) --
.

. , -
. -
625

,
.

(. ).
,
.
, .

A
A

(, -
). A : B D (. . 14.1).
: B, D.
.
B, , ;
, A B 6 .
,
A
-
D
, -
, 4 . :
A-D, 4 .
A-B, 6 .
;
.

A-D
A


D
. -
, A-D
( )?
. ?
, - ,
A

D
, -
. D,
B, , .
, B (6) D (4). ,
-
(. 14.4),
D

B
. , -
(X) B , D.
, , A-D
. ,
(
). A-D D.
?
.
, -
, .
; .
626 14.

. 14.4.

A-B

A
-
D

D
-
, D

.
B
,
C

E
. -
: 7, 8 12
. (, A ,
A-D .)

:
A-B, 6 .
D-B, 7 .
D-C, 8 .
D-E, 12 .
A-D?
; . ,
, .
? .
.

, A;

A
-
D
. -
A

-
B
, A


B
6 -
B.
. -
:
1. , , . ( -
, .)
627

2. , ,
, -
. .
3. , .
A, D B 1, C E 2,

F
3 (. 14.5). -
3 2, 2 1.

6 C

F
4
8
12
E


( )
( ) ( )

. 14.5.

B-E
A, D B
. A D 2,
B . B C E.
: C 10 , E
7. :
B-E, 7 .
D-C, 8 .
B-C, 10 .
D-E, 12 .
D-B , .
,
.
,
B
-
E
(7). -
E (. . 14.3).
628 14.

E-C

E
, C

5-
, F 7 . D-E , E
. :
E-C, 5 .
E-F, 7 .
D-C, 8 .
B-C, 10 .
E-C.
C.

C-F
.
:
C-F, 6 .
E-F, 7 .
C F, F
. ,
A-D, A-B, B-E, E-C C-F (. . 14.3). ,
.



.
, .


,
.

.
, ,
. ,
.
(.
12, ); .

.
629


(
).
, . -
:
1. ,
. .
2. . ,
, .
, -
. .
1 ,
. -
. 1 ,
.


,
. .
-
, , .
,
. ,

. ,
, 2.
GraphW


Workshop
. -
,
2.
. 14.1 , . 14.1 , -
.

14.1.
, -
(
)
1 AB6, AD4 AB6, AD4

2 DE12, DC8, DB7, AB6 DE12, DC8, AB6 DB7(AB6)


3 DE12, BC10, DC8, BE7 DC8, BE7 DE12(BE7), BC10(DC8)
4 BC10, DC8, EF7, EC5 EF7, EC5 BC10(EC5), DC8(EC5)
5 EF7, CF6 CF6 EF7
630 14.

, ,
. ,
. 1
( ) 2 (
, 1).
-
GraphW.
, , .
; -
, .
,
.


, 2
? , , -
, . ,
, .
, -
-. -
, ,
, .

Java
mstw()
. , -
, vertexList[],
0. currentVert ,
.
public void mstw() //
{
currentVert = 0; // 0

while(nTree < nVerts-1) //


{ // currentVert
vertexList[currentVert].isInTree = true;
nTree++;

// , currentVert
for(int j=0; j<nVerts; j++) //
{
if(j==currentVert) // ,
continue;
if(vertexList[j].isInTree) // ,
631

continue;
int distance = adjMat[currentVert][j];
if( distance == INFINITY) // ,
continue;
putInPQ(j, distance); //
}
if(thePQ.size()==0) // ?
{
System.out.println(" GRAPH NOT CONNECTED");
return;
}
//
Edge theEdge = thePQ.removeMin();
int sourceVert = theEdge.srcVert;
currentVert = theEdge.destVert;

//
System.out.print( vertexList[sourceVert].label );
System.out.print( vertexList[currentVert].label );
System.out.print(" ");
}

//
for(int j=0; j<nVerts; j++) //
vertexList[j].isInTree = false;
}
while,
. :
1. .
2. , , (
).
3. .
.
. 1
currentVert ( isInTree).
2 , , -
.
, currentVert.
, :
.
.
, .
, putInPQ()
. , ,
.
632 14.

3 .
, (currentVert)
.
mstw() ,
isInTree. ,
.

.
,
. putInPQ()
. find() PriorityQ,
. , find()
1, putInPQ() -
. , putInPQ() ,
.
, ,
, . putInPQ():
public void putInPQ(int newVert, int newDist)
{
// ?
int queueIndex = thePQ.find(newVert); //
if(queueIndex != -1) // ,
{ //
Edge tempEdge = thePQ.peekN(queueIndex);
int oldDist = tempEdge.distance;
if(oldDist > newDist) // ,
{
thePQ.removeN(queueIndex); //
Edge theEdge = new Edge(currentVert, newVert, newDist);
thePQ.insert(theEdge); //
}
// ;
}
else //
{ //
Edge theEdge = new Edge(currentVert, newVert, newDist);
thePQ.insert(theEdge);
}
}

mstw.java
PriorityQ .
, , , -
. PriorityQ .
find() .
peekN() , removeN()
633

. . -
14.1 mstw.java.
14.1. mstw.java
// mstw.java
//
// : C>java MSTWApp
////////////////////////////////////////////////////////////////
class Edge
{
public int srcVert; //
public int destVert; //
public int distance; //
// -------------------------------------------------------------
public Edge(int sv, int dv, int d) //
{
srcVert = sv;
destVert = dv;
distance = d;
}
// -------------------------------------------------------------
} // Edge
////////////////////////////////////////////////////////////////
class PriorityQ
{
// 0 size-1
private final int SIZE = 20;
private Edge[] queArray;
private int size;
// -------------------------------------------------------------
public PriorityQ() //
{
queArray = new Edge[SIZE];
size = 0;
}
// -------------------------------------------------------------
public void insert(Edge item) //
{
int j;

for(j=0; j<size; j++) //


if( item.distance >= queArray[j].distance )
break;

for(int k=size-1; k>=j; k--) //


queArray[k+1] = queArray[k];

queArray[j] = item; //
size++;
}

634 14.

14.1 ()
// -------------------------------------------------------------
public Edge removeMin() //
{ return queArray[--size]; }
// -------------------------------------------------------------
public void removeN(int n) // N
{
for(int j=n; j<size-1; j++) //
queArray[j] = queArray[j+1];
size--;
}
// -------------------------------------------------------------
public Edge peekMin() //
{ return queArray[size-1]; }
// -------------------------------------------------------------
public int size() //
{ return size; }
// -------------------------------------------------------------
public boolean isEmpty() // true,
{ return (size==0); }
// -------------------------------------------------------------
public Edge peekN(int n) // N
{ return queArray[n]; }
// -------------------------------------------------------------
public int find(int findDex) //
{ // destVert
for(int j=0; j<size; j++)
if(queArray[j].destVert == findDex)
return j;
return -1;
}
// -------------------------------------------------------------
} // PriorityQ
////////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
public boolean isInTree;
// -------------------------------------------------------------
public Vertex(char lab) //
{
label = lab;
isInTree = false;
}
// -------------------------------------------------------------
} // Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
635

private final int INFINITY = 1000000;


private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
private int currentVert;
private PriorityQ thePQ;
private int nTree; //
// -------------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = INFINITY;
thePQ = new PriorityQ();
}
// -------------------------------------------------------------
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end, int weight)
{
adjMat[start][end] = weight;
adjMat[end][start] = weight;
}
// -------------------------------------------------------------
public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}
// -------------------------------------------------------------
public void mstw() //
{
currentVert = 0; // 0

while(nTree < nVerts-1) //


{ // currentVert
vertexList[currentVert].isInTree = true;
nTree++;

// , currentVert
for(int j=0; j<nVerts; j++) //
{
if(j==currentVert) // ,

636 14.

14.1 ()
continue;
if(vertexList[j].isInTree) // ,
continue;
int distance = adjMat[currentVert][j];
if( distance == INFINITY) // ,
continue;
putInPQ(j, distance); //
}
if(thePQ.size()==0) // ?
{
System.out.println(" GRAPH NOT CONNECTED");
return;
}
//
Edge theEdge = thePQ.removeMin();
int sourceVert = theEdge.srcVert;
currentVert = theEdge.destVert;

//
System.out.print( vertexList[sourceVert].label );
System.out.print( vertexList[currentVert].label );
System.out.print(" ");
}

//
for(int j=0; j<nVerts; j++) //
vertexList[j].isInTree = false;
}
// -------------------------------------------------------------
public void putInPQ(int newVert, int newDist)
{
// ?
int queueIndex = thePQ.find(newVert); //
if(queueIndex != -1) // ,
{ //
Edge tempEdge = thePQ.peekN(queueIndex);
int oldDist = tempEdge.distance;
if(oldDist > newDist) // ,
{
thePQ.removeN(queueIndex); //
Edge theEdge = new Edge(currentVert, newVert, newDist);
thePQ.insert(theEdge); //
}
// ;
}
else //
{ //
Edge theEdge = new Edge(currentVert, newVert, newDist);
637

thePQ.insert(theEdge);
}
}
// -------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class MSTWApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addVertex('F'); // 5

theGraph.addEdge(0, 1, 6); // AB 6
theGraph.addEdge(0, 3, 4); // AD 4
theGraph.addEdge(1, 2, 10); // BC 10
theGraph.addEdge(1, 3, 7); // BD 7
theGraph.addEdge(1, 4, 7); // BE 7
theGraph.addEdge(2, 3, 8); // CD 8
theGraph.addEdge(2, 4, 5); // CE 5
theGraph.addEdge(2, 5, 6); // CF 6
theGraph.addEdge(3, 4, 12); // DE 12
theGraph.addEdge(4, 5, 7); // EF 7

System.out.print("Minimum spanning tree: ");


theGraph.mstw(); //
System.out.println();
}
} // MSTWApp
///////////////////////////////////////////////////////////////
main() MSTWApp , . 14.1. -
:
Minimum spanning tree: AD AB BE EC CF


, , ,
.
, -
.
, , .
638 14.


, -
, . ,
, ;
.
.

. . 14.6. , A B
$50, B D $90 . . ,
(
).
$60
B C

$50
$50

$90 $40
A

$80 $20

D E
$70

. 14.6.

. 14.6 . -
, ( )
. ,
A

B
-
, B A .
, .
, -
, -
.
. ,
A

E

D

, B

C, D

C

- -
. ( F ,
. ,
, .)
:
?
. 14.6 ,
A E D C $140.
639


, , -

. .

; -
. ,
, ,
.



( . , 1959 .) -
. ,
,
.


, , ,
A . ( )
, .
,
. -
, ( ) ,
.
,
( , ).
, , -
.
.
.

: A
, -
. A
. A , B $50, D
$80. (. 14.2).
640 14.

14.2. 1: A
A B C D E
1 50 ( A) 80 ( A)

; A ,
,
. ( ,
.) -
, .
, . ?
.

-
(A).

, , .
, -
( ).
() ,
A .

, A
, A
.

: B
A

B

($50). -
B, . ,
B C $60, D $90.
, A C B
$50+$60=$110, C. ,
A

D

B

$50+$90=$140. -
, A D $80.
A,
, . 14.3
, . 14.7 -
.
14.3. 2: A B
A B C D E
1 50 ( A) 80 ( A)
2 50 ( A)* 110 ( B) 80 ( A)
641

$110

$60
B C
$50

A $90

$80

D E


( )
( ) ( )

. 14.7. 2

, , , -
, .
? .
A B, .
A D,
B. D
B D. ,
A B .
, .
(*) , ,
.


:
1. ( ).
2. (-
).
3. .
A B 1,
. 1 ,
. (,
.)
, -
, 1. ,
A D $80, B C $60.
642 14.

D C , 2 (
).
E,
. . 14.7 -
.
,

, .

: D
A
A-D $80. A-B-C ($110)
A-B-D ($140) .
D $80. ,
D C ($20) E ($80).
C. A B $110.
, C $100 D.
A E $150 D.
(. 14.4 . 14.8).

14.4. 3: A, B D
A B C D E
1 50 ( A) 80 ( A)
2 50 ( A)* 110 ( B) 80 ( A)
3 50 ( A)* 100 ( D) 80 ( A)* 150 ( D)

$60
B C

$50

A $90

$20

$80

D E
$70

$100
$150

. 14.8. 3
643

: C
A
C D $100. C.
, C


E
$40. C

-
$100 A ( D), E $40 C,
A

E

$150 (
A
-
D
-
E
) $140 (-
A-D-C-E). . 14.5 . 14.9.

14.5. 4: A, B, D C
A B C D E
1 50 ( A) 80 ( A)
2 50 ( A)* 110 ( B) 80 ( A)
3 50 ( A)* 100 ( D) 80 ( A)* 150 ( D)
4 50 ( A)* 100 ( D)* 80 ( A)* 140 ( C)

$60
B C

$50

$90 $20 $40


A
$80 $140

$100 $70
D E

. 14.9. 4

: E
A ,
, E D C ($140). E,
, E ( B,

B
). 14.6 ; -
E, .

14.6. 4: A, B, D, C E
A B C D E
1 50 ( A) 80 ( A)
2 50 ( A)* 110 ( B) 80 ( A)

644 14.

14.6 ()
A B C D E
3 50 ( A)* 100 ( D) 80 ( A)* 150 ( D)
4 50 ( A)* 100 ( D)* 80 ( A)* 140 ( C)
5 50 ( A)* 100 ( D)* 80 ( A)* 140 ( C)*

, A
. . - -
-
A .
. -
:
,
, . -
( )
.

( ,
, ).

GraphDW Workshop
, ,
GraphDW Workshop. , .14.6.
, . 14.10. ( ,
, .) -
, ,
, .
, Path,
A. Path -
A ( ).


Path (. 14.10).

( ) . ( ,

View.) .

.
, . -
14.7 .
645

. 14.10. GraphDW

14.7. 1:
A B C D E
(A) 50 (A) (A) 80 (A) (A)


. ,
. -
A,
A .
( ,
A
-
A
), ( -
). : ,
, .
.


A ,
A

. A

B


D
, -
.
. Path ,
A (50) B.
, -
B .
646 14.

B

, B

-
. A B ,
.


, A, B.
, ,
. ,
(A B), . C.
, A-B (50) B-C (60)
A-C ().
C, (

C
).
A

B
50 ( -

B
), B


C
60 ( -
B C ). 110.
110 ,
C 110. B
C; B C.
D. , A-B (50)

B
-
D
(90)
A
-
D
(80). -
A D, 80 ( )
B ( A-B-D).
140 (50+90). 80, 80 .
E , A-B
(50)
B
-
E
() A

-
E
(). -
E ,
, . 14.8.

14.8. 2:
A B C D E
(A) 50 (A) 110 (B) 80 (A) (A)

, -
. A
. -
A. C B;
, A C B
C.
. (
A.)
647


-
( Path). ,
A 80 D.
D .


,
, ; -
C E. C E
.14.9.

14.9. 3:
A B C D E
(A) 50 (A) 100 (D) 80 (A) 150 (D)

A , , 100
C. C .

E. C;
. 14.10.

14.10. 3:
A B C D E
(A) 50 (A) 100 (D) 80 (A) 140 (C)


E
, . -
A

-
. AB, AD, DC CE,
.
. -
,
E

E
C

, -
. C ( )
D, D A. ,
A E A-D-C-E.
GraphDW; .
-
, .
648 14.

Java
,
.
, path()
, path() .

sPath DistPar
,

() . ,
-
. sPath[].
,
, , .
, .
( , -
).
C
100(
D
), , -
A C 100, D C
.

. DistPar;
sPath[].
class DistPar //
{ // sPath
public int distance; //
public int parentVert; //
public DistPar(int pv, int d) //
{
distance = d;
parentVert = pv;
}
}

path()
path() .
DistPar Vertex, mstw.
java (. 14.1). path() Graph,
mstw.java.
public void path() //
{
int startTree = 0; // 0
vertexList[startTree].isInTree = true;
649

nTree = 1; //

// adjMat sPath
for(int j=0; j<nVerts; j++)
{
int tempDist = adjMat[startTree][j];
sPath[j] = new DistPar(startTree, tempDist);
}

//
while(nTree < nVerts)
{
int indexMin = getMin(); // sPath
int minDist = sPath[indexMin].distance;

if(minDist == INFINITY) //
{ // ,
System.out.println("There are unreachable vertices");
break; // sPath
}
else
{ // currentVert
currentVert = indexMin; //
startToCurrent = sPath[indexMin].distance;
// startTree
// currentVert startToCurrent
}
//
vertexList[currentVert].isInTree = true;
nTree++;
adjust_sPath(); // sPath[]
}
displayPaths(); // sPath[]

nTree = 0; //
for(int j=0; j<nVerts; j++)
vertexList[j].isInTree = false;
}
0 vertexList[]. -
path() .
. Vertex
, . -
, nTree
. path()
sPath[]. 0,
, 0.
sPath[] -
A.
650 14.

while .
, .
:
1. sPath[] .
2. ( )
. , currentVert.
3. sPath[] current-
Vert.
path() , -
, , .
? ( while
), ;
.
, path()
sPath[] displayPaths(). -
. , path() nTree isInTree
, ( -
).

getMin()
sPath[] , path()
getMin(). sPath[]
( ) .
public int getMin() // sPath
{ //
int minDist = INFINITY; // ""
int indexMin = 0;
for(int j=1; j<nVerts; j++) //
{ //
if( !vertexList[j].isInTree && //
sPath[j].distance < minDist ) //
{
minDist = sPath[j].distance;
indexMin = j; //
}
}
return indexMin; //
} //
-
,
. getMin() ; -
.
, .
651

sPath[] adjust_sPath()
adjust_sPath() sPath[]
, .
currentVert , startToCurrent
sPath[] . adjust_sPath() -
sPath[], column.
sPath[] , ,
:
1. ( startToCur-
rent) currentVert column.
startToFringe.
2. startToFringe sPath[].
3. startToFringe , sPath[].
. sPath[] -
, .
adjust_sPath():
public void adjust_sPath()
{
// sPath
int column = 1; //
while(column < nVerts) //
{
// column ,
if( vertexList[column].isInTree )
{
column++;
continue;
}
// sPath
// currentVert column
int currentToFringe = adjMat[currentVert][column];
//
int startToFringe = startToCurrent + currentToFringe;
// sPath
int sPathDist = sPath[column].distance;

// sPath
if(startToFringe < sPathDist) // ,
{ // sPath
sPath[column].parentVert = currentVert;
sPath[column].distance = startToFringe;
}
column++;
}
}
652 14.

main() path.java , . 14.6,


. :
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex(A); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4

theGraph.addEdge(0, 1, 50); // AB 50
theGraph.addEdge(0, 3, 80); // AD 80
theGraph.addEdge(1, 2, 60); // BC 60
theGraph.addEdge(1, 3, 90); // BD 90
theGraph.addEdge(2, 4, 40); // CE 40
theGraph.addEdge(3, 2, 20); // DC 20
theGraph.addEdge(3, 4, 70); // DE 70
theGraph.addEdge(4, 1, 50); // EB 50

System.out.println("Shortest paths");
theGraph.path(); //
System.out.println();
}
:
A=inf(A) B=50(A) C=100(D) D=80(A) E=140(C)

path.java
14.2 path.java.
.

14.2. path.java
// path.java
//
// : C>java PathApp
////////////////////////////////////////////////////////////////
class DistPar //
{ // sPath
public int distance; //
public int parentVert; //
// -------------------------------------------------------------
public DistPar(int pv, int d) //
{
distance = d;
parentVert = pv;
}
653

} // DistPar
///////////////////////////////////////////////////////////////
class Vertex
{
public char label; // (, 'A')
public boolean isInTree;
// -------------------------------------------------------------
public Vertex(char lab) //
{
label = lab;
isInTree = false;
}
// -------------------------------------------------------------
} // Vertex
////////////////////////////////////////////////////////////////
class Graph
{
private final int MAX_VERTS = 20;
private final int INFINITY = 1000000;
private Vertex vertexList[]; //
private int adjMat[][]; //
private int nVerts; //
private int nTree; //
private DistPar sPath[]; //
private int currentVert; //
private int startToCurrent; // currentVert
// -------------------------------------------------------------
public Graph() //
{
vertexList = new Vertex[MAX_VERTS];
//
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
nTree = 0;
for(int j=0; j<MAX_VERTS; j++) //
for(int k=0; k<MAX_VERTS; k++) //
adjMat[j][k] = INFINITY; //
sPath = new DistPar[MAX_VERTS]; // shortest paths
}
// -------------------------------------------------------------
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}
// -------------------------------------------------------------
public void addEdge(int start, int end, int weight)
{
adjMat[start][end] = weight; // ( )
}

654 14.

14.2 ()
// -------------------------------------------------------------
public void path() //
{
int startTree = 0; // 0
vertexList[startTree].isInTree = true;
nTree = 1; //

// adjMat sPath
for(int j=0; j<nVerts; j++)
{
int tempDist = adjMat[startTree][j];
sPath[j] = new DistPar(startTree, tempDist);
}

//
while(nTree < nVerts)
{
int indexMin = getMin(); // sPath
int minDist = sPath[indexMin].distance;

if(minDist == INFINITY) //
{ // ,
System.out.println("There are unreachable vertices");
break; // sPath
}
else
{ // currentVert
currentVert = indexMin; //
startToCurrent = sPath[indexMin].distance;
// startTree
// currentVert startToCurrent
}
//
vertexList[currentVert].isInTree = true;
nTree++;
adjust_sPath(); // sPath[]
}

displayPaths(); // sPath[]

nTree = 0; //
for(int j=0; j<nVerts; j++)
vertexList[j].isInTree = false;
}
// -------------------------------------------------------------
public int getMin() // sPath
{ //
int minDist = INFINITY; // ""
int indexMin = 0;
655

for(int j=1; j<nVerts; j++) //


{ //
if( !vertexList[j].isInTree && //
sPath[j].distance < minDist ) //
{
minDist = sPath[j].distance;
indexMin = j; //
}
}
return indexMin; //
} //
// -------------------------------------------------------------
public void adjust_sPath()
{
// sPath
int column = 1; //
while(column < nVerts) //
{
// column ,
if( vertexList[column].isInTree )
{
column++;
continue;
}
// sPath
// currentVert column
int currentToFringe = adjMat[currentVert][column];
//
int startToFringe = startToCurrent + currentToFringe;
// sPath
int sPathDist = sPath[column].distance;

// sPath
if(startToFringe < sPathDist) // ,
{ // sPath
sPath[column].parentVert = currentVert;
sPath[column].distance = startToFringe;
}
column++;
}
}
// -------------------------------------------------------------
public void displayPaths()
{
for(int j=0; j<nVerts; j++) // display contents of sPath[]
{
System.out.print(vertexList[j].label + "="); // B=
if(sPath[j].distance == INFINITY)
System.out.print("inf"); // inf

656 14.

14.2 ()
else
System.out.print(sPath[j].distance); // 50
char parent = vertexList[ sPath[j].parentVert ].label;
System.out.print("(" + parent + ") "); // (A)
}
System.out.println("");
}
// -------------------------------------------------------------
} // Graph
////////////////////////////////////////////////////////////////
class PathApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 ( )
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4

theGraph.addEdge(0, 1, 50); // AB 50
theGraph.addEdge(0, 3, 80); // AD 80
theGraph.addEdge(1, 2, 60); // BC 60
theGraph.addEdge(1, 3, 90); // BD 90
theGraph.addEdge(2, 4, 40); // CE 40
theGraph.addEdge(3, 2, 20); // DC 20
theGraph.addEdge(3, 4, 70); // DE 70
theGraph.addEdge(4, 1, 50); // EB 50

System.out.println("Shortest paths");
theGraph.path(); //
System.out.println();
}
} // PathApp
////////////////////////////////////////////////////////////////



13 , ,
.
, :
?
, , -
.
657


.
.
, path.java
. . 14.11.

14.11.
A B C D E

A 50 100 80 140
B 60 90 100
C 90 180 40
D 110 20 60
E 50 110 140

,
( )
.
,
1962 . . 14.11.
.
.14.11 .

. 14.11.

, .
,
. , . 14.11 ,
B C 30 (10 B D 20 D C).
, -
. .
(, 30 C A),

C
( 30 C

). -
C (40 D) , C A
30, D C 40. ,
D A 70. .14.12
. 14.11.
658 14.

. 14.12. : ) y = 2, x = 0, z = 3; ) y = 3, x = 0, z = 1; ) y = 3, x = 2, z = 1

A , . B A 70,
D 10, B , B
, B.
C 30 A.
C D 20.
C A ( 30) D C 20; , D A
50.
D .
A 50. , B D
10; ,
B

A
60. -
70. 60 70, 70
60.
.
,
,
, . -
.

-
, .
: .

O(V2), V . ?
, -
,
. ,
, V2 .
659

O(V2) . -
. (
, -
.)
. -
,
, -
,
.
-
.
: ,
.

O(V+E), V , E -
.
O((E+V)logV).

. , -
, -
.
(. )
.
, -
. O(V3), -
.


: O(1) O(N),
O(N*logN), O(N2) ( ) O(N3).
O(N3) N
.
.
,
, -
N. , ,
- .
. - -
,
( , ).
660 14.


( 13.5 13)
- -
.
, . -
, ,
8. , ,
, .
8,
. ( ), -
.
63 . ,
263, 1019.
, 106. 107 ,
1013 . , -
106 ( ) .

.
(.. , 1823) ,
.


: ,
, .
.
. ,
. -
, ?
.
. 14.13 .

A
-
A? : ,
.

. 14.13.
661

,
(
A
-
B
-
C
,
B
-
C
-
A
,
C
-
B
-
A
..), -
. ABCEDA
318. ABCDEA - E A.
, : -
( ).
6 , 6 , 5-
, 4 .; 6*5*4*3*2*1, 720 .
50 .
,
. -
: ,
. , A B

B
A

, . -
, ;
.


, ,
. ,
, .
. -
, ; ,
. . 14.13 ABCEDA ,
ABCDEA
. -
( ,
).
O(N!),
. O- , 2N N!,
; 2N .

, .
, , .
,
.
-
.
-
, .
662 14.

-
.

.

.

( -
).

.
.
. -

.

.
.
1. _______ .
2. -
:
a) ;
b) , ;
c) ;
d) , .
3.
(/).
4.
?
5. , -
, :
a) ;
b) ;
c) ;
d) .
6.
, , _________ .
663

7. -
(/).
8. :
a) ;
b) ;
c) ,
;
d) ,
.
9. , -
, (/).
10. :
a) , ;
b) ;
c) ;
d) .
11. -
:
a) ;
b) ;
c) ,
;
d) , -
.
12. , _______ -
.
13. ________ .
14. ( O-)
?
15. ABCEDA . 14.13
?

.
.
1. GraphW Workshop
. 14.6.
( ).
664 14.

2. . 14.6
GraphDW
Workshop

, , -
100.
3. .
, .
.


,

.
14.1. path.java (. 14.2),
-
. , ,
A.
14.2. -
. -
Java: Vertex ,
.
,
. , . main()
main() path.java (. 14.2):
, . 14.6, addVer-
tex() addEdge(). ,
, . - .
Edge ,
. Edge (
, ).
14.3. . path.java (. -
14.2) . ,
. ,
, .
. -
. main()
.
14.4. (.
). ,
N, 10 . -
.
.
anagram.java (. 6.2) 6, . -
.
665

;
, ,
. (-
, ABCDEA, AEDCBA).
14.5. ,
.
15

, -
.
.
, , -
. .
, ,
.
:
: , , ,
-.
: , , ,
.
: , , ,
, .
: , .
: , -
, B-, .


: , -
, , ..,
.
: , , -.
,
.

667

( ,
).

? . 15.1,
, , . -
, ,
.

. 15.1.



: , -
, - . . 15.1
, .
. -,
-
. , -
, - .

O(N), , , -
.
668 15.


, -
. -
.
( 1965 ) ,
18 . -
,
, .
,
100 . , -
10000 .
, -
.
( ).
.
.
, (
, ).
, .
, ,
?
, ,
. ,
, .

Java
Java ,
Java ,
. , -
, .
, , -
. Java ,
.
, , C++
. -
, , .


.
, Vector, Stack Hashtable Java. C++
669

STL

(
Standard
Template

Library

) -
.
( )
, .
(,
) (, )
. , -
.


. , :
;
.
;
, -
.
, .
, .
,
.
,
.
( Vector Java) ,
. ,
, -
.


, -
.
,
;
, .
.
( ,
), , ,
.
, ,
-.
670 15.


, ,
.
(O(logN)) , .
O(N), (
). -
.
,
, , , -
O(N) , .
, ,
.


-
2-3-4. ,
O(logN) ,
.
( -). ,
, .

.
-.
- .
:
AVL, (splay) .., ,
- .

-
- ,
, -
, . -

, -
.
- , , -
. , -
,
. -
.
- ,
.
671

,
.
-,
. , -
; ,
, .
- , -
/ . ,
.



15.1 -
.

15.1.

O(N) O(1) O(N)
O(logN) O(N) O(N) O(N)
O(N) O(1) O(N)
O(N) O(N) O(N) O(N)
( ) O(logN) O(logN) O(logN) O(N)
( ) O(N) O(N) O(N) O(N)
( O(logN) O(logN) O(logN) O(N)
)
- O(1) O(1) O(1)

, -
. ,
-
.
; ,
.


, ,
, .
, .
-
672 15.

. , 13,
, 14, , ,
.
, -
(ADT), : ,
( ) .
, ,
:
: .
: .
: .
-
. -
(, ),
.

.

, -
. , LIFO (Last In, First
Out).
.
, ,
. ,
-
.
, -
(, , ),
.
, ,
( -
). ,
,
-
.

, -
. , FIFO (First In,
First Out).
673

, ,
. . -
.
,
.
, (
) . -
, , .


, , -
, (
) .

. ,
. ,
O(logN).
,
.
, .
, .
15.2.

( O(1) O(1) ,
)
( O(1) O(1) ,
)
O(N) O(1)
( )
O(logN) O(logN)
()

, , -
, . , -

. ( ,
1000.)
-
;
674 15.

, O(N). -
.
,
.
.
, 5000 .
,
:
, .
, -
, ,

. ,
O(N2). -
.
.
,
.
15.3 -
. -
O-. (
- .)

15.3.



O(N2) O(N2)
O(N2) O(N2)

O(N2) O(N2)
3/2 3/2
O(N ) O(N )
2
O(N*logN) O(N )
O(N*logN) O(N*logN)

O(N*logN) O(N*logN)

. -

. -
675

.
.
,
, .
:
. ,
( ) ( ).

O(V2), V . -
O(V+E), E
.
O(V2)
O((E+V)logV) -
. V E ,
.


, -
.
,
. 10,
2-3-4 11, -.
,
. (
, .) , ,
, .
,
, ,
. ,
.


,
.
.
, ( ) -
.
,

O(N).
.
676 15.


.
, -
. -
, ,
O(1).

( , ..).
,
.
,
.
, - -
. ,
, -
. ,
.

B-
B- ,
; .
,
, . B- ,
O(logN)
. ,
B- .

,
, -
. ,
(O(1)), .
. 15.2 -
.



. -
, ,

677

. ,
.
, -
,
, .

. 15.2.

, ,
,
. ,
, -
, ,
.
, .

.
, -
, , .
.

Workshop


Workshop .
Workshop -
.
, , -
Java.
Sun Microsystems Java 2 Standard Edition (J2SE)
Software Development Kit (SDK),
,
.
- -
(www.piter.com) Sams www.samspublishing.com.

Workshop
(
applet
) Java

-, -
. -,
-
.

Workshop
, -
, . , 8,
,
Workshop
, -
.
,
, ..
Workshop.
Workshop
,
Microsoft
Internet

Explorer

Netscape

Communica-

tor. Java-
. ,
Workshop
-
appletviewer SDK.
Sun Microsystems SDK 679

Workshop

, -
.
Workshop , .class,
.html. .html.
.


,
, ,
Java
. , -
.
Java ,
. ; ,
, -
. Windows MS-
DOS. .
. ,
, .

Sun Microsystems SDK


Workshop,
, Sun SDK. SDK -
Sun www.sun.com ( Java 2 Standard Edition
(J2SE) SDK). ,
,
Java-.


SDK ,
. Windows
MS-DOS.
. .
MS-DOS cd -
, Workshop -.
SDK,
.
680 . Workshop


Windows SDK
PATH autoexec.bat. ,
. PATH
autoexec.bat
SDK
. , -

SET PATH=C:\JDK1.4.0\BIN;
autoexec.bat SET PATH. autoexec.bat -
. ,
. (
.)

Workshop
Workshop SDK,
cd MS

-
DOS
. , -
Array Workshop 2, , :
C:\>cd javaapps
C:\javaapps>cd chap02
C:\javaapps\chap02>cd Array
.html appletviewer SDK:
C:\javaapps\chap02\Array>appletviewer Array.html
, . -
, .
, -
HTML Java.
, Workshop

-
.

Workshop

Workshop
. -
. , Ins
Array Workshop . ,
, .
, ,
. ,
Find,
, Press any button.
, -
Ins.
Sun Microsystems SDK 681

3, , 7,
, Step .
Run -
. Run ,
. ,
Step, Run.
Workshop ,
. -
.


- .java
c .class. .java , -
. .class
Java.
.class -
Java Sun SDK. .class
App; .
( cd)
App. , insertSort ( 3)
InsertSort 3 (
Work-
shop !). .java .class,
insertSortApp.class.
C:\chap03\InsertSort>java insertSortApp
. insertSort -
.
.


, -
.
, . Java-
javac, .java-. ,
insertSort, insertSort
C:\chap03\insertSort>javac insertSort.java
.java .
.java .class -

. ,
.
682 . Workshop


-
.java. , MS-DOS edit
Windows.
.
(, Microsoft Word)
. ,
,
Java .



Ctrl+C. ,
(,
Enter
), -
Ctrl+C.



Workshop
-
.class . ,
. Workshop
, .
,
.
, , .
, .


Sun SDK, Java Symantec,
Microsoft, Borland .. Sun
Java, Sun ONE Studio 4 ( Forte).
, SDK.
, .
,
,
Java
1.4.0 . -
( , ,
) ,
Java. (, ,
1, , .java -
.)

,
, .
; .


-
(Donald E. Knuth) The Art of Computer Programming
( Addison Wesley, 1998).
1970- , .
: ,
. 3 .
-
, ,
.
(Robert Sedgewick)
Algorithms in C++ ( Addison Wesley, 1998).
Algorithms ( Addison Wesley,
1988), Pascal

. -
. ( , ) -
, .
Algorithms in Java (Robert Sedgewick)
(Michael Schidlowsky) ( Addison Wesley, 2002)
Java.

(Janet J. Prichard) (Frank M. Carrano)
Data Abstraction and Problem Solving with C++: Walls and Mirrors (
Benjamin
Cummings

, 2001). , -
.
Java Data Abstraction and Problem Solving with Java: Walls and Mirrors.
(
Bryan

Flamig
)
Practical

Algorithms

in

C
++ (-
John Wiley and Sons, 1995)
, ,
.
(
Jon

Louis

Bentley
)
Programming

Pearls
(-
Addison

Wesley

, 1999) 1986 , -
684 .

.
.

(Timothy A. Budd) Classic Data Structures in C++ (
Addison Wesley, 2000), (Mark Allen Weiss) Data Structures
and Problem Solving Using C++ ( Addison Wesley, 1999)
(
Yedidyah

Langsam
) .
Data Structures Using C and C++ (
-
Prentice Hall, 1996).

-


Java
- -
(Stephen Gilbert)
(Bill McCarty) Object-Oriented Programming in Java (
Waite Group Press, 1997).
C++, Object-
Oriented
Programming

in

C

++, Fourth

Edition

(- -
C++. .: , 2011).
(Ken Arnold), (James Gosling)
(David Holmes) Java Programming Language, Third Edition (
Addison Wesley, 2000) Java. ,
( ): ,
Sun Microsystems, Java.
(Cay S. Horstmann)
(
Gary

Cornell
)
Core

Java
2, Fifth


Edition
(
Prentice

Hall
, 2000) -
, , -
Java.

-


(Scott W. Ambler) The Object Primer: The Application Developers Guide
to Object-Orientation, Second Edition ( Cambridge University Press,
2001). , -
.
- .
Object-Oriented Design in Java
( Waite Group Press, 1998) .
- 685

(Grady Booch) Object-Oriented Analysis and Design with


Applications ( Addison Wesley, 1994)
- .
, -
. , ,
.
- ,
(
Frederick

P
.
Brooks
,
Jr
.)
The

Mythical

Man
-
Month
(-
Addison Wesley, 1975, 1995),
.
,
.
, - -
, (Timothy Budd) An
Introduction to Object-Oriented Programming, Third Edition ( Addison
Wesley
, 2002); (
Arthur

J
.
Riel
)
Object
-
Oriented

Design

Heuris-
tics ( Addison Wesley, 1996); (Erich Gamma)
. Design Patterns: Elements of Reusable Object-Oriented Software (
- , .: , 2011).

1.
1) , ,
2) .
3) c
4)
5) b
6) a
7) d
8)
9)
10)

2.
1) d
2)
3) b
4)
5) new
6) d
7)
8) d
9)
10) 3
11) b
12) 6
13)
14) a
4. 687

15)
16)

3.
1) d
2) , ,
3)
4) a
5)
6) b
7)
8)
9) , outer.
10) c
11) d
12)
13) b
14) , outer, .
15) b

4.
1) 10
2) b
3) Last In, First Out First In, First Out
4) ,
5) b
6)
7) 45
8) , O(1).
9) c
10) O(N)
11) c
12)
688 .

13) b
14) ,
15) a

5.
1) b
2)
3) d
4) 2
5) 1
6) c
7) current.next=null;
8) Java.
9) a
10)
11) .
12) , .
13) .
14) b
15) , . push() pop()
O(1), .

6.
1) 10
2) d
3) 2
4) 10
5)
6) "ed"
7) b
8) c
9)
10)
8. 689

11)
12) c
13) b
14) b
15)

7.
1) c
2) 40
3) d
4)
5) O(N*logN), O(N2)
6) a
7)
8) d
9)
10) c
11)
12) b
13)
14) log2N
15) true

8.
1) O(logN)
2) b
3)
4) 5
5) c
6) ,
7) a
8) c
9)
690 .

10) A, A
11) d
12) 2*n+1
13)
14)
15) c

9. -
1) ( )
2) b
3)
4) d
5) b
6) ,
7)
8) a
9) ,
10) d
11) ,
12) b
13)
14) a
15)

10. 2-3-4
1) b
2)
3) 2
4)
5) b
6)
7) a
8) 2
12. 691

9)
10) b
11) O(logN)
12) d
13)
14)
15) a

11. -
1) O(1)
2) -
3) d
4)
5) 1, 4, 9, 16, 25
6) b
7)
8) 1.0
9)
10) d
11)
12)
13) a
14)
15)

12.
1) b
2) , .
3)
4) a
5) a
6) c
7) ( )
692 .

8)
9) b
10)

13.
1) ,
2) 2 (,
).
3)
4) d
5) A:B, B:A>C>D, C:B, D:B
6) a
7) 3
8) c
9)
10)
11)
12) d
13) ( )
14) , .

14.
1)
2) d
3)
4)
5) b
6)
7)
8) a
9)
10) a
11) b
14. 693

12)
13)
14) 2N, N 1
15)

.
,
, ,
, C++ Interactive Course

Object
-
Oriented
Programming

in

C

++ (- -
C++. .: , 2011).
Assembly Language Primer for the IBM PC and XT
( ) Soul of CP/M.

2-3, , 462 , 25, 28


2-3-4, , 436 O-, 79
, 439 , 316
, 440 , 639
, 440 , 622
, 436 , 659
, 461 (), 583
appletviewer, , 678 , 309
autoexec.bat, , 680 , 262
AVL, , 432 , 115
B-, 471 , 252
, 472 , Java, 39
, 676 ,
, 472 , 152
, 475 ,
double, , 43 , 365
for, , 96
Java
new, , 39 , 36
, 39 , 29
, 41 , 468
main(), 35 , 470
, 40 , 479
, 37
new, , 535
Java, 39 , 316
, 52 , 316
n-, 300 , 309
SDK, 678 , 337
throws IOException, 42


, 208 , 43
, 42
ADT, 208 , 41
, 58 , 43
696

, , 669 , 499
, 574 , 507
, 580 , 499
, 645
, 575

, 608
, 377 , 509
, 637
, 351
, 622 , 359
, 658 , 667, 670
, 676 , 382
, 535 , 391
, 466 , 361
, 417 , 542
, 417 , 356
, 381
2-3-4 , 439 , 347
B-, 472 , 368
, 217 , 379
, 48 , 65
, 359 O-, 80
, 637 , 72
, 639 , 257
, 217, 226
, 196
, , 639
, 146
, 661

, 520
AVL, 432
, , 528
, 403
, 574
, 351
, 674

, 607
, 382

- , 407
, 599
, 577
, 582
, 583 , 660
, 592 , 668
, 578 , 29
, 659
, 580
, 575
, 575
, 604 , 97
697

() - , 403, 457
2-3-4 , 457
, 111 , 408
, 103 , 439
, 407
, 52 , 457
-, 535 , 403
, 53 , 415
, 431
ADT, 208
, 58
, 153
, , 115
, 314 , 495
, 226 , 499
, 499
, 64

, 507 2-3-4 , 436
, 32 B-, 476
, 63 , 72
, 56 , 308
, 58
, 226
, 128
, 207 , 669
, 33 , 381
, 80
private, 35 , 53
public, 35 , 80
, 30 , 52
, 509 , 55
, 350 , 52
, 487 , 182
-, 526 , 55
, , 487
, 302 , 79
, 494 , 250
, 181 , 579
, 645 , 327
, 679 , 494
, O-, 81 , 530
, 35
, 58 , 599
, 518 , 35
698


, 577 , 186
,
, 314 , 468
, 36 , 477
, 659 , , 132
, 403 , 413, 420

, 31
, 30
, , 129
, 252


, 583
, 564
, 592
, 562
, 361
, 542
, 31
, 547
, 32
, 542
, 52
, 560
, 33
, 544
, 32

, 112
, 417

, 417
new, 39
- , 408
, 40

(=), 38
2-3-4 , 439
, 161
B-, 472
(.), 33
, 48

, 65
, 318
, 476
(%), , 492
, 64
, 494
, 533
, 509
, 36

, 29
, 507
, 181
, 495
, 339

, 339
, 530
, 340
, 136
, 333
, 672
,
, 146
, 262
, 592
, 469
, 136
, 153, 366
, 140

, 146
, 349
2-3-4, 436
699

() ()
- , 406 , 267
, 353 , 250
, -, 407 , 262
, 373 , 645
, 366 (
), 349
ADT, 208
, 55
, 146
, 673 AVL, 432
, 542 , 670
, 152 , , 530
, Java, 38
, 37 , 669
, 36 , 346
, 116 , 196
, 527 , 226
, 200
, 30 , 615
, 30 , , 391
, 31 , 682
, 89 (), 575
, 97 , 546
, 97 , 209
, 215
, 111
, 309 , 87
, 316
, 132 , 479
, 673
2-3 , 465 , 104
- , 431 , 98
, 141 , 112
, 579 , 116
, 622 , 89
, 580 , 309
, 267
, 599 , 674
, 575 , 299
, 264 , 215
, 214
, 252 , 98
, 257 , 103
, 289 , 103
700

, 267
, 479 , 489
, 279 , 604
, 278 , 608
, 299
n-, 300
, 39
, 302 , 347
, 308 2-3-4 , 436
, 359
ADT, 208 , 350
, 209 , 348
, 53 - , 406
, 579 , 350
, 544
, 115 , 450
, 403 , 356
, 279 , 350
, 349
Java, 38 , 459
, , 668 , 368
, 227 , 350
, 122 , Java, 38
, 672 , 63
, 281 , 346
, 161 , 65
, 136 , 65
, 72
, 129
, 489
, 528
, 25 , 250
, 670
, 666 , 31
, 672 -, 493
, 673
, 671
, 672 , 262
, 27 , 264
-, 670 , , 391
, 36 487
, 36 , 535
, 36 , 676
701

()
, 494 , 140
, 517 (
, 495 ), 608
, 530 , 258
-, 487 , 407
-, 493
, 526
, 526 , , 299
, 530
, 526
, 316
, , 577

Java.
Computers Science.
2-

computer science

.
.
.
.
.
.

, 192102, -, . (. ), . 3, , . 7.
005-93, 2; 95 3005 .
26.06.13. 70100/16. . . . 56,760. 1000.

. 142300, , , . , . , . 1.

Вам также может понравиться