Professional Documents
Culture Documents
Data Structure & Algorithm
Data Structure & Algorithm
JJCAO
for i = 1:n,
k = i
//invariant: a[k] smallest of a[i..n]
for j = i+1:n
if a[j] < a[k] then k = j
//invariant: a[1..i] in final
position
swap a[i,k]
end
3
How is Data Represented?
• Sort a sequences: Array? List? Heap?
4
Elementary Data Structures
• Arrays
• Lists
• Stacks
• Queues
• Trees
6
Data Type vs. Data Structure
• Data Structure is the way an ADT is
implemented.
• Must be distinguished from the ADT
itself!
7
C++ Implementation of Stack
8
Data Structure vs. Algorithm
• Data Structures
– Represent objects of the ADT
• Algorithms
– Manipulate the data structures to
implement a mission using the operations of
the ADT
9
Contiguous vs. Linked Data
Structures
Data structures can be neatly classified as either
contiguous or linked depending upon whether they
are based on arrays or pointers:
10
Array
Array of integer
Array of images
m _ pData a0 a1 a2 am 2 am 1
𝑚_𝑛𝑆𝑖𝑧𝑒
数据区
Advantages of contiguously-
allocated arrays
1. Constant-time access given the index.
m _ pData a0 a1 a2 am 2 am 1
m _ nMax n
m _ nSize m 数据区 备用区
14
Remove an Element
15
Notes
• Practical implementations usually include
more operations
• Initialization/Destruction
• “Luxury” operations:
– size()
– print()
– operators
16
Bubble Sort
Bubble sort: beginning of
first pass:
18
Several Sort Algorithms
http://www.sorting-algorithms.com 19
The Linked List Structures
typedef struct list {
item type item;
struct list *next;
} list;
Note the **l, since the head element of the list changes.
22
Deleting from a List
23
Deleting from a List
24
Advantages of Linked Lists
1. Overflow on linked structures can never
occur unless the memory is actually full.
25
Various List
26
Stack
• last-in, first-out (LIFO)
27
Stack ADT & std::vector
29
Stack Example 1: Reversing a
Word
• part
• trap
30
Stack Example 2: Delimiter
Matching
• When compilers compile your code
• When you want to write a program to
parse a math formula
31
Stack Example 2: Delimiter
Matching
• A successful example: b(c[d]e)
Character Read Stack Contents
b
( (
c (
[ [(
d [(
] (
e (
)
32
Queue
• first-in, first-out
33
Implementation of Queue
34
A Circular Queue
35
Homework 1
• Basic Dynamic Array & Selection Sort
• Deadline: 22:00, Sep. 10, 2011
36