data structure & algorithm

36
Data Structure & Algorithm Lecture 2 – Basic Data Structure JJCAO Steal some from Prof. Yoram Moses

Upload: gage-barnes

Post on 02-Jan-2016

43 views

Category:

Documents


1 download

DESCRIPTION

Data Structure & Algorithm. Lecture 2 – Basic Data Structure JJCAO. Steal some from Prof. Yoram Moses. The Sorting Problem. Example: Input: A sequence of n numbers Output : A permutation (reordering) of the input sequence such that. Recitation. Selection Sort. Insertion Sort. - PowerPoint PPT Presentation

TRANSCRIPT

Introduction to C & C++

Data Structure & AlgorithmLecture 2 Basic Data Structure

JJCAOSteal some from Prof. Yoram Moses1The Sorting Problem2

Recitationk=i

for i = 1:n, k = i //invariant: a[k] smallest of a[i..n] for j = i+1:nif a[j] < a[k] then k = j //invariant: a[1..i] in final position swap a[i,k] end

key = A[j]3

How is Data Represented?Sort a sequences: Array? List? Heap?

There are many optionsEfficiency of the algorithm also depends on the data structure used4Elementary Data StructuresArraysListsStacksQueuesTrees5Mankinds progress is measured by the number of things we can do without thinking.

In some languages or libs, some of them are the off-the-shelf components.

56

Components of Data StructureThere are two aspects to any data structure:The abstract operations which it supports. (Abstract Data Types, ADT)The implementation of these operations. (Data Structure)Data structures such as array, list, stacks, 6Data Type vs. Data StructureData Structure is the way an ADT is implemented.Must be distinguished from the ADT itself!7

C++ Implementation of Stack8

Data Structure vs. AlgorithmData StructuresRepresent objects of the ADT

AlgorithmsManipulate the data structures to implement a mission using the operations of the ADT9Contiguous vs. Linked Data StructuresData structures can be neatly classified as either contiguous or linked depending upon whether they are based on arrays or pointers:

Contiguously-allocated structures are composed of single slabs of memory, and include arrays, matrices, heaps, and hash tables.Linked data structures are composed of multiple distinct chunks of memory bound together by pointers, and include lists, trees, and graph adjacency lists.10ArrayAn array is a number of data items of the same type arranged contiguously in memory.Fixed-size

Array of imagesArray of integer

11Advantages of contiguously-allocated arraysConstant-time access given the index.

Space efficiency - Arrays consist purely of data, so no space is wasted with links or other formatting information.

Memory locality - Physical continuity (memory locality) between successive data accesses helps exploit the high-speed cache memory on modern computer architectures.12Dynamic Array

131 + 2 + 4 + 8 + + 2^i =2^{i+1}=n => i = log(n)How much total workThe apparent waste in this procedure involves the recopying of the old contents on each expansion.If half the elements move once, a quarter of the elements twice, and so on, the total number of movements M is given by

Thus each of the n elements move an average of only twice, and the total work of managing the dynamic array is the same O(n) as a simple array.14

Remove an Element15

NotesPractical implementations usually include more operationsInitialization/DestructionLuxury operations:size()print()operators16Bubble SortBubble sort: beginning of first pass:

1. Compare two players.2. If the one on the left is taller, swap them.3. Move one position right.17

End of first pass

Bubble Sortfor i = 1:n, swapped = false for j = n:i+1, if a[j] < a[j-1], swap a[j,j-1] swapped = truebreak if not swapped end18Is there any problem?18Several Sort Algorithms

19http://www.sorting-algorithms.comhttp://www.sorting-algorithms.com19The Linked List Structurestypedef struct list {item type item;struct list *next;} list;20

Pointers represent the address of a location in memory.A cell-phone number can be thought of as a pointer to its owner as they move about the planet.Searching a ListSearching in a linked list can be done iteratively or recursively.

list *search_list(list *l, item type x){if (l == NULL) return(NULL);if (l->item == x)return(l);elsereturn( search_list(l->next, x) );}21Insertion into a ListSince we have no need to maintain the list in any particularorder, we might as well insert each new item at the head.

void insert_list(list **l, item_type x){list *p = new list;p->item = x;p->next = *l;*l = p;}

Note the **l, since the head element of the list changes.22Deleting from a List23

Deleting from a List24

Advantages of Linked ListsOverflow on linked structures can never occur unless the memory is actually full.

2. Insertions and deletions are simpler than for contiguous (array) lists.

3. With large records, moving pointers is easier and faster than moving the items themselves.25Various List26

26Stacklast-in, first-out (LIFO)27

http://www.algolist.net/Data_structures/Stack27Stack ADT & std::vector28Stack ADTstd::vectorcommentscreate()constructor of vectorcreates empty stackbool isEmpty() empty()tells whether the stack s is emptypush(Item e) push_back(Item e)put e on top of the stack sItem peek() Item back()returns topmost element in stack spop() pop_back()removes topmost element from the stack sdestroy() Deconstructor of vectordestroys stack s

reserve()push_back()pop_back()back()size()empty()

28Stack Implementation Using a Linked List29

Stack Example 1: Reversing a Wordparttrap

30Stack Example 2: Delimiter MatchingWhen compilers compile your codeWhen you want to write a program to parse a math formula

31Stack Example 2: Delimiter MatchingA successful example: b(c[d]e)

32Character ReadStack Contentsb((c([[(d[(](e()Queuefirst-in, first-out33

Implementation of Queue34

A Circular Queue35

Homework 1Basic Dynamic Array & Selection SortDeadline: 22:00, Sep. 10, 201136