Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A17/18 – Revision.

Slides:



Advertisements
Similar presentations
Lecture 22, Revision 1 Lecture notes Java code – CodeFromLectures folder* Example class sheets – 4 of these plus solutions Extra examples (quicksort) Lab.
Advertisements

Introduction to Algorithms Quicksort
Data Structures Using C++ 2E
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
Data Structures Data Structures Topic #13. Today’s Agenda Sorting Algorithms: Recursive –mergesort –quicksort As we learn about each sorting algorithm,
CSE1303 Part A Data Structures and Algorithms Lecture A7 – Nodes and Linked Structures.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A15 – Hash Tables: Collision Resolution.
More on Data Structures in C CS-2301 B-term More on Lists and Trees Introduction to Hash Tables CS-2301, System Programming for Non-majors (Slides.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
CSE1303 Part A Data Structures and Algorithms Lecture A13 – Binary Search Trees (Information Retrieval)
1 COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf.
CSE1303 Part A Data Structures and Algorithms Lecture A17/18 – Revision.
CSE1303 Part A Data Structures and Algorithms Lecture A11 – Recursion.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A8 – Linked Stacks and Linked Queues.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A9 – Linked Lists.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A10 – Elementary Algorithms (Revision)
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A11 – Recursion.
More on Data Structures in C CS-2301 D-term More on Data Structures in C CS-2301 System Programming D-term 2009 (Slides include materials from The.
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
CSE1303 Part A Data Structures and Algorithms Lecture A9 – Linked Lists.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A5 – Basic Data Structures – Continued (Lists)
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Final Review Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2010.
Information and Computer Sciences University of Hawaii, Manoa
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
1 Lecture 11 POLYNOMIALS and Tree sort 2 INTRODUCTION EVALUATING POLYNOMIAL FUNCTIONS Horner’s method Permutation Tree sort.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
TECH Computer Science Dynamic Sets and Searching Analysis Technique  Amortized Analysis // average cost of each operation in the worst case Dynamic Sets.
Starting at Binary Trees
Hash Tables: Collision Resolution. 2 Overview Hash Tables Collisions Linear Probing Problems with Linear Probing Chaining.
1 10. Binary Trees Read Sec A. Introduction: Searching a linked list. 1. Linear Search /* Linear search a list for a particular item */ 1. Set.
Hashing Hashing is another method for sorting and searching data.
Final Exam Review CS Total Points – 60 Points Writing Programs – 50 Points Tracing Algorithms, determining results, and drawing pictures – 50.
© 2006 Pearson Education Chapter 10: Non-linear Data Structures Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
Programming Practice 3 - Dynamic Data Structure
Hash Table March COP 3502, UCF 1. Outline Hash Table: – Motivation – Direct Access Table – Hash Table Solutions for Collision Problem: – Open.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables IV.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
 Saturday, April 20, 8:30-11:00am in B9201  Similar in style to written midterm exam  May include (a little) coding on paper  About 1.5 times as long.
Final Exam Review CS Total Points – 20 Points Writing Programs – 65 Points Tracing Algorithms, determining results, and drawing pictures – 50.
Data Structure and Algorithms
SUYASH BHARDWAJ FACULTY OF ENGINEERING AND TECHNOLOGY GURUKUL KANGRI VISHWAVIDYALAYA, HARIDWAR.
Final Exam Review CS 3358.
Chapter 12 – Data Structures
Non Linear Data Structure
Lecture No.45 Data Structures Dr. Sohail Aslam.
Linked Lists.
Week 11 - Friday CS221.
Hashing Exercises.
Teach A level Computing: Algorithms and Data Structures
Chapter 20: Binary Trees.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Chapter 21: Binary Trees.
EE 312 Final Exam Review.
Presentation transcript:

Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A17/18 – Revision

2 Lecture Overview Subject overview –Topics covered this semester. Exam overview –Types of questions found in Part A of the exam. Exam hints and resources –How to deal with exams (resources, and hints for during the exam). –How to prepare. Revision Going further –Some examples you may find useful.

3 Subject Overview Basic C –Data types –1D and multidimensional arrays –Strings –I/O & File I/O –Structures and typedef –Dynamic memory –Pointers

4 Subject Overview ADTs –Stacks Array implementation Linked implementation Push Pop Initialise Check empty/full

5 Subject Overview ADTs –Queues Array implementation Linked implementation Append Serve Initialise Check empty/full

6 Subject Overview ADTs –Singly linked list Array implementation Linked implementation Insert Delete Search Initialise Check empty/full Traversal

7 Subject Overview ADTs –Doubly linked list Linked implementation Insert (not C code) Delete (not C code) Search (not C code) Initialise Traversal (not C code)

8 Subject Overview ADTs –Trees Parse Trees/Expression Trees –Prefix/Infix/PostFix Binary Trees and Binary Search Trees –Insert –Delete –Search –Initialise –PreOrder, InOrder, PostOrder Traversal

9 Subject Overview ADTs –Hashtables Hash function Insert Delete (chaining) Search Initialise Collision resolution (chaining, linear probing)

10 Subject Overview Algorithms –Searching Linear search (arrays, lists, hashtable) Binary search (arrays) –Recursion Direct/Indirect Unary Binary –Complexity

11 Subject Overview Algorithms –Sorting Insertion sort (array) Selection sort (array) Binary Tree sort Mergesort (array) Quicksort (array)

12 Exam Overview 0.5 of the 3 hour exam is for Part A Typical types of questions: –Multiple choice –Short Answer Write a structure or a small piece of C Write a short answer to a question –Long answer Code a solution to a problem Write an algorithm for a problem Fill in diagrams/missing code We will go over the sample exam next lecture.We will go over the sample exam next lecture.

13 Resources for Exams Monash Community services self-help information for exams: –Exam Skills - Clue WordsExam Skills - Clue Words –Exam Taking TechniquesExam Taking Techniques –Exam AnalysisExam Analysis –Effective Skills in ExaminationsEffective Skills in Examinations –How to Survive Exam WeeksHow to Survive Exam Weeks –Preparing for Tests and ExamsPreparing for Tests and Exams –Final Exam Review ChecklistFinal Exam Review Checklist –Examination Room TechniquesExamination Room Techniques –General Exam taking HintsGeneral Exam taking Hints –How to keep Calm during TestsHow to keep Calm during Tests –Test Anxiety ScaleTest Anxiety Scale All these resource pages found at: –

14 Exam Preparation Hints Revise all of the lecture notes Do all of the tutorial questions Revise and finish all of the pracs (you gain better understanding doing the bonus questions) Do the suggested reading at the end of all lectures Do the suggested additional exercises in the tutorials Attempt the practice exam Revise your tests (look at them at the general office) Try to implement the algorithms that you haven't already done in the pracs Prepare questions for the last tutorial Come with questions to consultation with the lecturers (additional hours are advertised closer to the exam date)

15 During the Exam Read the questions carefully!Read the questions carefully! If you don't know what a question means, ask the lecturer. Don't get stuck on one question – move onto something else. Plan your time – don't spend it all on a couple of questions. Do the easy questions first. Attempt all questions. Don't use whiteout! (And don't erase your workings) Check you have answered all the questions.

16 Revision – Linked Lists Operations: –Initialise –Set position (step to a position in the list) –Insert –Search –Delete –Make a new node

17 void initialiseList(List* listPtr) { listPtr->headPtr = NULL; listPtr->count = 0; } Initialise List count headPtr 0 NULL listPtr addr of list

18 Set Position Head position Node* setPosition(const List* listPtr, int position){ int i; Node* nodePtr = listPtr->headPtr; if (position = listPtr->count) { fprintf(stderr, “Invalid position\n”); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } return nodePtr; }

19 Set Position Head position Node* setPosition(const List* listPtr, int position){ int i; Node* nodePtr = listPtr->headPtr; if (position = listPtr->count) { fprintf(stderr, “Invalid position\n”); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } return nodePtr; } nodePtr

20 Set Position Head position Node* setPosition(const List* listPtr, int position){ int i; Node* nodePtr = listPtr->headPtr; if (position = listPtr->count) { fprintf(stderr, “Invalid position\n”); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } return nodePtr; } nodePtr

21 Set Position Head position Node* setPosition(const List* listPtr, int position){ int i; Node* nodePtr = listPtr->headPtr; if (position = listPtr->count) { fprintf(stderr, “Invalid position\n”); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } return nodePtr; } nodePtr

22 Inserting – Start of List Head 0x30a8 0x2008 0x position 0x2000 newNodePtr

23 Inserting – Start of List Head 0x30a8 0x2008 0x position 0x2000 newNodePtr

24 Inserting – Start of List Head 0x30a8 0x2008 0x position 0x2000 newNodePtr

25 Inserting – Inside the List 0x position 0x2000 newNodePtr Head 0x3050 0x3080

26 Inserting – Inside the List 0x position 0x2000 newNodePtr Head 0x3050 0x3080

27 Inserting – Inside the List 0x position 0x2000 newNodePtr Head 0x3050 0x3080

28 void insertItem(List* listPtr, float item, int position) { Node* newNodePtr = makeNode(item); Node* nodePtr = NULL; if (position == 0) { newNodePtr->nextPtr = listPtr->headPtr; listPtr->headPtr = newNodePtr; } else { nodePtr = setPosition(listPtr, position-1); newNodePtr->nextPtr = nodePtr->nextPtr; nodePtr->nextPtr = newNodePtr; } listPtr->count++; }

29 Deleting – 1 st Node Head 0 position 0x4000 nodePtr 0x30a80x20300x4000

30 Head 0 position 0x4000 nodePtr 0x30a80x20300x4000 Deleting – 1 st Node

31 Head 0 position 0x4000 nodePtr 0x30a80x2030 Deleting – 1 st Node

32 Deleting – Middle Node Head 1 position 0x2030 nodePtr 0x30a80x20300x4000 prevNodePtr

33 Head 1 position 0x2030 nodePtr 0x30a80x20300x4000 Deleting – Middle Node 0x4000 prevNodePtr

34 Head 1 position 0x2030 nodePtr 0x30a80x4000 Deleting – Middle Node 0x4000 prevNodePtr

35 void deleteNode(List* listPtr, int position) { Node* prevNodePtr = NULL; Node* nodePtr = NULL; if (listPtr->count > 0 && position count) { if (position == 0) { nodePtr = listPtr->headPtr; listPtr->headPtr = nodePtr->nextPtr; } else { prevNodePtr = setPosition(listPtr, position - 1); nodePtr = prevNodePtr->nextPtr; prevNodePtr->nextPtr = nodePtr->nextPtr; } listPtr->count--; free(nodePtr); } else { fprintf(stderr, “List is empty or invalid position.\n”); exit(1); }

36 Doubly Linked List currentPtr 01234

37 struct DoubleLinkNodeRec { float value; struct DoubleLinkNodeRec* nextPtr; struct DoubleLinkNodeRec* previousPtr; }; typedef struct DoubleLinkNodeRec Node; struct DoubleLinkListRec { int count; Node* currentPtr; int position; }; typedef struct DoubleLinkListRec DoubleLinkList;

38 Insert at end currentPtr newNodePtr 0x40000x30800x20300x2000 0x40000x3080 0x2030 NULL 0x2000 prevNodePtr 0x2030

39 Insert at end 0x40000x30800x20300x2000 0x40000x3080 0x2030 0x2000 NULL 0x2000 0x2030 currentPtr newNodePtr prevNodePtr

40 Insert at end 0x40000x30800x20300x2000 0x40000x3080 0x2030 0x2000 NULL 0x2030 0x2000 0x2030 currentPtr newNodePtr prevNodePtr

41 Insert inside the list 0x40000x3080 0x2030 0x2000 0x4000 0x3080 0x2030 NULL 0x2000 0x3080 currentPtr newNodePtr prevNodePtr

42 Insert inside the list 0x40000x3080 0x2030 0x2000 0x4000 0x3080 0x2030 NULL 0x2030 NULL 0x2000 0x3080 currentPtr newNodePtr prevNodePtr

43 Insert inside the list 0x40000x3080 0x2030 0x2000 0x4000 0x3080 0x2030 NULL 0x2030 0x3080 0x2000 0x3080 currentPtr newNodePtr prevNodePtr

44 Insert inside the list 0x40000x3080 0x2030 0x2000 0x4000 0x2000 0x30800x2030 NULL 0x2000 0x3080 currentPtr 0x2030 0x3080 newNodePtr prevNodePtr

45 Insert inside the list 0x40000x3080 0x2030 0x2000 0x4000 0x2000 0x30800x2000 NULL 0x2000 0x3080 currentPtr 0x2030 0x3080 newNodePtr prevNodePtr

46 Delete from start 0x40000x30800x2030 0x40000x3080 0x2030 NULL oldNodePtr 0x4000 currentPtr

47 Delete from start 0x40000x30800x2030 0x40000x3080 NULL 0x4000 0x2030 currentPtr oldNodePtr

48 Delete from start 0x3080 NULL 0x4000 0x2030 0x3080 NULL currentPtr oldNodePtr

49 Delete from inside list oldNodePtr 0x40000x30800x2030 0x40000x3080 0x2030 NULL 0x3080 currentPtr

50 Delete from inside list 0x40000x30800x2030 0x40000x3080 0x2030 NULL 0x3080 currentPtr oldNodePtr

51 Delete from inside list 0x40000x30800x2030 0x4000 0x2030 NULL 0x3080 currentPtr oldNodePtr

52 Delete from inside list 0x40000x2030 0x4000 0x2030 NULL 0x3080 currentPtr oldNodePtr

53 Revision – Recursion -Unary -calls itself at most once -Binary/N-ary -calls itself twice/N times -Direct -the function calls itself -Indirect -The function calls another function which calls the first function again.

54 Revision – Recursion -Always -Converges to a base case (always) -Has a recursive definition -Has a base case -Can remove recursion using a stack instead -Disadvantages -May run slower -May use more space -Advantages -Easier to prove correct -Easier to analyse

55 Recursive - Free List nodePtr /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } 0x258a0x4c68 0x2000 Stack in memory 0x2000

56 Recursive - Free List 0x258a0x4c68 0x2000 0x258a 0x2000 Stack in memory /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } nodePtr

57 Recursive - Free List 0x258a0x4c68 0x2000 0x4c68 0x258a 0x2000 Stack in memory /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } nodePtr

58 Recursive - Free List 0x258a0x4c68 0x2000 NULL 0x4c68 0x258a 0x2000 Stack in memory /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } nodePtr

59 Recursive - Free List /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } 0x258a0x4c68 0x2000 0x4c68 0x258a 0x2000 Stack in memory nodePtr

60 Recursive - Free List 0x258a 0x2000 0x258a 0x2000 Stack in memory /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } nodePtr

61 Recursive - Free List 0x2000 Stack in memory /* Delete the entire list */ void FreeList(Node* nodePtr) { if (nodePtr==NULL) return; FreeList(nodePtr->next); free(nodePtr); } nodePtr

62 Revision - Binary Trees Parent nodes always have 2 children Expression Tree –A Binary Tree built with operands and operators. –Also known as a parse tree. –Used in compilers. Binary Search Tree –Every node entry has a unique key. –All the keys in the left subtree of a node are less than the key of the node. –All the keys in the right subtree of a node are greater than the key of the node

63 Revision - Binary Trees Traversal –PreOrder (Visit Left Right) –InOrder (Left Visit Right) –PostOrder (Left Right Visit)

64 Example: Expression Tree / + / 1 3* /3 + 6*7 / 4 1/3+*67/4 Infix /1367*4/+ Postfix +/13/*674 Prefix

65 Revision – Binary Search Trees Operations: –Initialise –Insert –Search –Delete (not needed to be known for exam) –Make a new node –Traverse (inorder, preorder, postorder)

66 Make a new node Steps: –allocate memory for the new node –put item into the new node –set left and right branches to NULL returns: pointer to (i.e. address of) new node newNodePtr NULL 0x2000 newNodePtr 0x2000 newNodePtr NULL value 3.3 TreeNode* makeTreeNode(float value) { TreeNode* newNodePtr = NULL; newNodePtr = (TreeNode*)malloc(sizeof(TreeNode)); if (newNodePtr == NULL){ fprintf(stderr, “Out of memory\n”); exit(1); } else{ newNodePtr->key = value; newNodePtr->leftPtr = NULL; newNodePtr->rightPtr = NULL; } return newNodePtr; }

67 TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr; }Insert Insert 0.9 nodePtr

68Insert TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr; } Insert 0.9 nodePtr

69Insert TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr; } Insert 0.9 nodePtr

70Insert TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr; } Insert 0.9 nodePtr

71Insert TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr; } Insert 0.9 nodePtr 0.9

72Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.7 nodePtr

73Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.7 nodePtr

74Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.7 nodePtr

75Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.7 nodePtr

76Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.5 nodePtr

77Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.5 nodePtr

78Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.5 nodePtr

79Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.5 nodePtr

80Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } Find 0.5 nodePtr

81Traversal Inorder traversal of a Binary Search Tree always gives the sorted order of the keys. (left, visit, right) void printInorder(TreeNode* nodePtr){ printInorder(nodePtr->leftPtr); printf(“ %f, nodePtr->key); printInorder(nodePtr->rightPtr); } Preorder (visit, left, right): void printPreOrder(TreeNode* nodePtr){ printf(“ %f, nodePtr->key); printPreOrder(nodePtr->leftPtr); printPreOrder(nodePtr->rightPtr); } Postorder (left, right, visit): void printPostOrder(TreeNode* nodePtr){ printPostOrder(nodePtr->leftPtr); printPostOrder(nodePtr->rightPtr); printf(“ %f, nodePtr->key); }

82 Revision - Hash Tables Each item has a unique key. Use a large array called a Hash Table. Use a Hash Function –Use prime numbers –Maps keys to positions in the Hash Table. –Be easy to calculate. –Use all of the key. –Spread the keys uniformly. –Use unsigned integers Operations: –Insert –Delete –Search –Initialise

83 unsigned hash(char* s){ int i = 0; unsigned value = 0; while (s[i] != ‘\0’){ value = (s[i] + 31*value) % 101; i++; } return value; } Example: Hash Function for a string

84 Linear Probing - Insert Apply hash function to get a position. Try to insert key at this position. Deal with collision –When two keys are mapped to the same position. –Very likely Linear Probing - Search Apply hash function to get a position. Look at this position. Deal with collision –When two keys are mapped to the same position. –Very likely Linear Probing - Delete Use the search function to find the item If found check that items after that also don’t hash to the item’s position If items after do hash to that position, move them back in the hash table and delete the item.

85 Aho, Kruse, Standish, Horowiz, Langsam, Sedgewick, Knuth Example: Insert with Linear Probing Langsam hash table 5 Aho Kruse Standish Horowitz Hash Function Langsam module insert(hashTable, item) { position = hash(item) initialise count to 0 while(count < hashTableSize) { if (position in hashTable is empty) { write item at position in hashTable exit loop } else { step position along (wrap around) increment count } if (count == hashTableSize) then the hashTable is full }

86 Example: Search with Linear Probing Langsam hash table 5 Aho Kruse Standish Horowitz Hash Function Langsam module search(hashTable, target) { position = hash(target) initialise count to 0 while (count < hashTableSize) { if (position in hashTable is empty) return -1; else if (key at position in hashTable == target) return position; step position along (wrap around) increment count } if (count == hashTableSize) then return -1; }

87 Hashtable with Chaining At each position in the array you have a list: List hashTable[MAXTABLE]; Advantages –Insertions and deletions are quick & easy –Resizable Disadvantages –Uses more space –More complex to implement :

88 Insert with Chaining Apply hash function to get a position in the array. Insert key into the Linked List at this position in the array. void InsertChaining(Table* hashTable, float item) { int posHash = hash(item) ListInsert (hashTable[posHash], item); } Knuth 1 Standish Aho Sedgewick :

89 Search with Chaining Apply hash function to get a position in the array. Search the Linked List at this position in the array to see if the item is in it. /* module returns NULL if not found, or the address of the * node if found */ Node* SearchChaining(Table* hashTable, float item){ posHash = hash(item) Node* found; found = searchList (hashTable[posHash], item); return found; } Knuth 1 Standish Aho Sedgewick :

90 Delete with Chaining Apply hash function to get a position in the array. Delete the item in the Linked List at this position in the array. /* module uses the Linked list delete function to delete * an item inside that list, it does nothing if that item * isn’t there. */ void DeleteChaining(Table* hashTable, float item){ int posHash = hash(item) deleteList (hashTable[posHash], item); } Knuth 1 Standish Aho Sedgewick :

91 Revision - Mergesort Recursively split the array in half until you have arrays of length 1 Merge them together in sorted order Return the merged array void mergeSort(float array[], int size){ int* tmpArrayPtr = (int*)malloc(size*sizeof(int)); if (tmpArrayPtr != NULL) mergeSortRec(array, size, tmpArrayPtr); else{ fprintf(stderr, “Not enough memory to sort list.\n”); exit(1); } free(tmpArrayPtr); } mergeList tmp: array:

92 Revision - Mergesort void mergeSortRec(float array[], int size, float tmp[]){ int i; int mid = size/2; if (size > 1) { mergeSortRec(array, mid, tmp); mergeSortRec(array+mid, size-mid, tmp); mergeArrays(array, mid, array+mid, size-mid, tmp); for (i = 0; i < size; i++) array[i] = tmp[i]; } SortSortSort SortSortSortSort Combine CombineCombine

93 Revision - Mergesort void mergeArrays(float a[],int aSize,float b[],int bSize,float tmp[]){ int k, i = 0, j = 0; for (k = 0; k < aSize + bSize; k++) { if (i == aSize) { tmp[k] = b[j]; j++; } else if (j == bSize) { tmp[k] = a[i]; i++; } else if (a[i] <= b[j]) { tmp[k] = a[i]; i++; } else { tmp[k] = b[j]; j++; } a: b: 378 tmp: Combine

94 Revision - Quicksort Partition –Choose a pivot element –Swap pivot with array[0] –Sort remaining elements so that the ones less than the pivot are to the left of the ones that are greater than the pivot. –Swap the pivot back into the correct position (the rightmost less than element) Sort the sub-array to the left of the pivot Sort the sub-array to the right of the pivot x < ppp <= x Partition Sort

95 Revision - Quicksort x < ppp <= x Partition Sort void quickSort(float array[], int size){ int index; if (size > 1){ index = partition(array, size); quickSort(array, index); quickSort(array+index+1, size - index - 1); } }

Revision – Quicksort - Partition int partition(float array[], int size){ int k; int mid = size/2; int index = 0; swap(array, array+mid); for (k = 1; k < size; k++){ if (list[k] < list[0]){ index++; swap(array+k, array+index); } } swap(array, array+index); return index; } p p0 px < pp <= x px < pp <= x px < pp <= x 96

97 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4030 NULL Head 91062

98 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4030 NULL Head curprev next

99 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4030 NULL Head curprev step next

100 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x4030 NULL Head curprev step next

101 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 NULL Head curprev step next

102 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 NULL Head curprev step next

103 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 NULL Head cur prev step

104 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 0x2030 Head cur prev step

105 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 0x2030 Head cur prev step

106 Going Further (not examinable) Insertion sort on a linked list 0x40000x30800x2030 0x30800x20300x4000 0x4030 0x2030 Head

107 Going Further (not examinable) Code for a doubly linked list follows on the next two slides.

108 /* Not examinable */ void insert(DoubleList* listPtr,float item,int position) { Node* newNodePtr = makeNode(item); Node* nodePtr = NULL; if (position == 0) { newNodePtr->nextPtr = listPtr->headPtr; if (listPtr->headPtr != NULL) listPtr->headPtr->previousPtr = newNodePtr; listPtr->headPtr = newNodePtr; } else { nodePtr = setPosition(listPtr, position-1); newNodePtr->nextPtr = nodePtr->nextPtr; newNodePtr->previousPtr = nodePtr; nodePtr->nextPtr->previousPtr = newNodePtr; nodePtr->nextPtr = newNodePtr; } listPtr->count++; }

109 /* Not examinable */ void deleteNode(DoubleList* listPtr, int position) { Node* oldNodePtr = NULL; Node* nodePtr = NULL; if (listPtr->count > 0 && position count) { if (position == 0) { oldNodePtr = listPtr->headPtr; listPtr->headPtr = oldNodePtr->nextPtr; if (listPtr->headPtr != NULL) listPtr->headPtr->previousPtr = NULL; } else { nodePtr = setPosition(listPtr, position - 1); oldNodePtr = nodePtr->nextPtr; nodePtr->nextPtr = oldNodePtr->nextPtr; oldNodePtr->nextPtr->previousPtr = nodePtr; } listPtr->count--; free(oldNodePtr); } else { fprintf(stderr, “List is empty or invalid position.\n”); exit(1); }