ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: http://people.math.yorku.ca/~zyang/itec2620m.htm Office: DB 3049
Sorting
Key Points Recursive sorting algorithms Achieving leverage Quicksort Mergesort
Review Previous sorting algorithms were O(n2) on average. What if we could get O(nlogn) Where have we seen O(logn) before? Binary search How did binary search work? first query explores 1 element second query explores 2 elements third query explores 4 elements
Recursive Sorting Split the elements into smaller sub-groups Partially sort each sub-group Trust recursion to put everything back together
Quicksort Algorithm Pick an element partially sort them move all larger elements on one side, and smaller elements on the other have to look at all elements to get one element in position Pick one element in each sub-division (2) move all elements as before (twice) have to look at half of the elements to get each new element into position Pick one element in each sub-division (4) move all elements as before (four times)
Quicksort Algorithm (Cont’d) Each sub-division is being sorted by the same algorithm as the overall set recursion base case is 0 or 1 elements – already sorted Work to sort each element is cut in half each level down Get twice as much done for our effort How many times can we cut something in half? O(logn) Pseudocode
Mergesort Algorithm Divide what you have to do into two halves sort each half merge the two halves into a fully sorted set Each half will be sorted by the same algorithm as the overall set recursion base case is 0 or 1 elements – already sorted Each upward merge sorts twice as much How many times can we cut something in half? O(logn) Pseudocode
Binary Search Trees
Key Points Inserting and Deleting into Linked Structures Linked lists Basic BST operations Deleting from BSTs
Codes Inserting into a Linked List Deleting from a Linked List Inserting into a BST insertion always happens at the bottom of the tree new node will be a leaf node Deleting from a BST – target node has less than two children Deleting from a BST – target node has two children Deleting from a BST – a better way