LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

Similar documents
MERGESORT & QUICKSORT cs2420 Introduction to Algorithms and Data Structures Spring 2015

Sorting. Task Description. Selection Sort. Should we worry about speed?

Quicksort. The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:

Sorting Algorithms. + Analysis of the Sorting Algorithms

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

About this exam review

Back to Sorting More efficient sorting algorithms

Programming II (CS300)

S O R T I N G Sorting a list of elements implemented as an array. In all algorithms of this handout the sorting of elements is in ascending order

CS 61B Summer 2005 (Porter) Midterm 2 July 21, SOLUTIONS. Do not open until told to begin

Mergesort again. 1. Split the list into two equal parts

// walk through array stepping by step amount, moving elements down for (i = unsorted; i >= step && item < a[i-step]; i-=step) { a[i] = a[i-step];

Better sorting algorithms (Weiss chapter )

CMSC 341 Lecture 7 Lists

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

DATA STRUCTURES AND ALGORITHMS

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Lecture Notes 14 More sorting CSS Data Structures and Object-Oriented Programming Professor Clark F. Olson

Divide and Conquer Algorithms: Advanced Sorting. Prichard Ch. 10.2: Advanced Sorting Algorithms

Topic 17 Fast Sorting

Faster Sorting Methods

CS 171: Introduction to Computer Science II. Quicksort

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Design and Analysis of Algorithms Assignment-2 Solutions (Hints) REMARK: Quicksort

Assignment 4: Question 1b omitted. Assignment 5: Question 1b clarification

CSE 332: Data Structures & Parallelism Lecture 12: Comparison Sorting. Ruth Anderson Winter 2019

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

Lecture 7: Searching and Sorting Algorithms

cmpt-225 Sorting Part two

Programming II (CS300)

Sorting. Order in the court! sorting 1

Quicksort. Repeat the process recursively for the left- and rightsub-blocks.

Mergesort again. 1. Split the list into two equal parts

Sorting and Searching

Outline. Quadratic-Time Sorting. Linearithmic-Time Sorting. Conclusion. Bubble/Shaker Sort Insertion Sort Odd-Even Sort

Quicksort (Weiss chapter 8.6)

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

A Linked Structure. Chapter 17

CSE 373 NOVEMBER 8 TH COMPARISON SORTS

CS171 Midterm Exam. October 29, Name:

Divide and Conquer Algorithms: Advanced Sorting

Introduction to Computer Science II CS S-20 Linked Lists III

Programming II (CS300)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Final Examination CS 125 Introduction to Computer Science Fall Hours

Divide and Conquer Sorting Algorithms and Noncomparison-based

CSE 2123 Sorting. Jeremy Morris

Sorting Algorithms Day 2 4/5/17

Data Structures Brett Bernstein

Merge Sort. Algorithm Analysis. November 15, 2017 Hassan Khosravi / Geoffrey Tien 1

SORTING. Insertion sort Selection sort Quicksort Mergesort And their asymptotic time complexity

Sorting. Order in the court! sorting 1

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

Sorting. Weiss chapter , 8.6

Overview of Sorting Algorithms

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

CSE143 Notes for Monday, 7/06/15

CSE373: Data Structure & Algorithms Lecture 18: Comparison Sorting. Dan Grossman Fall 2013

Key question: how do we pick a good pivot (and what makes a good pivot in the first place)?

Sorting. CSE 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation. CSE143 Au

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

CSC 172 Data Structures and Algorithms. Lecture #8 Spring 2018

Data structures. More sorting. Dr. Alex Gerdes DIT961 - VT 2018

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

ECE 242 Data Structures and Algorithms. Advanced Sorting II. Lecture 17. Prof.

CS 307 Midterm 2 Spring 2008

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture

CSE 143. Two important problems. Searching and Sorting. Review: Linear Search. Review: Binary Search. Example. How Efficient Is Linear Search?

We can use a max-heap to sort data.

CS 151 Name Final Exam December 17, 2014

COMP 250. Lecture 6. doubly linked lists. Sept. 20/21, 2017

ECE 242 Data Structures and Algorithms. Advanced Sorting I. Lecture 16. Prof.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

An Introduction to Data Structures

Sort: Divide & Conquer. Data Structures and Algorithms Emory University Jinho D. Choi

CSE373: Data Structure & Algorithms Lecture 21: More Comparison Sorting. Aaron Bauer Winter 2014

CS 311 Data Structures and Algorithms, Spring 2009 Midterm Exam Solutions. The Midterm Exam was given in class on Wednesday, March 18, 2009.

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Chapter 5. Quicksort. Copyright Oliver Serang, 2018 University of Montana Department of Computer Science

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

Cosc 241 Programming and Problem Solving Lecture 17 (30/4/18) Quicksort

Sorting. Bringing Order to the World

Searching and Sorting

Summer Final Exam Review Session August 5, 2009

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

Computer Science 136. Midterm Examination

Unit Outline. Comparing Sorting Algorithms Heapsort Mergesort Quicksort More Comparisons Complexity of Sorting 2 / 33

Merge- and Quick Sort

Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray();

Programming II (CS300)

Sorting: Quick Sort. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Sorting. Bubble Sort. Pseudo Code for Bubble Sorting: Sorting is ordering a list of elements.

Sorting. Lecture10: Sorting II. Sorting Algorithms. Performance of Sorting Algorithms

Lecture Notes on Quicksort

CSCI-1200 Data Structures Spring 2017 Lecture 15 Problem Solving Techniques, Continued

CS 171: Introduction to Computer Science II. Quicksort

Transcription:

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015 1

administrivia 2

-assignment 5 due tonight at midnight -assignment 6 is out -YOU WILL BE SWITCHING PARTNERS! 3

assignment 2 scores number of students score 4

assignment 3 scores number of students score 5

last time 6

mergesort divide and conquer quicksort another divide and conquer 7

mergesort 1)divide the array in half 2)sort the left half 2) take the left half, and go back to step 1 until??? 3)sort the right half 4)merge the two halves together 3) take the right half, and go back to step 1 until??? what does this look like? watch a video online 8

void mergesort(int[] arr, int left, int right) { // arrays of size 1 are already sorted if(start >= end) return; } int mid = (left + right) / 2; mergesort(arr, left, mid); mergesort(arr, mid+1, right); merge(arr, left, mid+1, right); divide conquer 9

void merge(int[] arr, start, mid, end) { // create temp array for holding merged arr int[] temp = new int[end start + 1]; int i1 = 0, i2 = mid; while(i1 < mid && i2 < end) { put smaller of arr[i1], arr[i2] into temp; } } copy anything left over from larger half to temp; copy temp over to arr; 10

notes on merging -the major disadvantage of mergesort is that the merging of two arrays requires an extra, temporary array -this means that mergesort requires 2x as much space as the array itself -can be an issue if space is limited! -an in-place mergesort exists, but is complicated and has worse performance -to achieve the overall running time of O(N log N) it is critical that the running time of the merge phase be linear 11

quicksort 1)select an item in the array to be the pivot 2)partition the array so that all items less than the pivot are to the left of the pivot, and all the items greater than the pivot are to the right 3)sort the left half 4)sort the right half 3) take the left half, and go back to step 1 until??? 4) take the right half, and go back to step 1 until??? what does this look like? watch a video online 12

void quicksort(int[] arr, int left, int right) { // arrays of size 1 are already sorted if(start >= end) return; } int pivot_index = partition(arr, left, right); quicksort(arr, left, pivot_index-1); quicksort(arr, pivot_index+1, right); what is the divide step? what is the conquer step? 13

in-place partitioning 1)select an item in the array to be the pivot 2)swap the pivot with the last item in the array (just get it out of the way) 3)step from left to right until we find an item > pivot -this item needs to be on the right of the partition 4)step from right to left until we find an item < pivot -this item needs to be on the left of the partition 5)swap items 6)continue until left and right stepping cross 7)swap pivot with left stepping item 14

choosing a pivot -the median of all array items is the best possible choice why? -is time-consuming to compute -finding true median is O(N) -it is important that we avoid the worst case -what IS the worst case(s)? -middle array item is a safe choice why? -median-of-three: pick a few random items and take median -why not the first, middle, and last items? -random pivot: faster than median-of-three, but lower quality 15

quicksort vs mergesort 16

-both are O(N log N) in the average case -mergesort is also O(N log N) in the worst case -so, why not always use mergesort? -mergesort requires 2N space -and, copying everything from the merged array back to the original takes time -quicksort requires no extra space -thus, no copying overhead! -but, in O(N 2 ) worst case <wha wha> 17

-both are divide and conquer algorithms (recursive) -mergesort sorts on the way up -after the base case is reached, sorting is done as the calls return and merge -quicksort sorts on the way down -once the base case is reached, that part of the array is sorted -though quicksort is more popular, it is not always the right choice! 18

today 19

-memory allocation -linked structures -linked lists -insertion & deletion -implementation details -doubly linked lists -LinkedList vs ArrayList 20

memory primer -all data in your program resides in memory at some point during its life -think of memory as giant blocks of bytes -each byte has its own memory address -addresses are just numbers [0 num_bytes] -byte n is next to byte n-1 and n+1 -ie. memory is ordered 21

memory in Java 22

-what actually happens when you use the new keyword? -new instructs the system to find a contiguous block of bytes big enough to hold whatever you are creating -int arr[] = new int[10]; -finds a block of memory big enough to hold 10 ints -arr[0] is right next to arr[1] in memory -the addresses of these two numbers are contiguous! 23

-arrays are a random access data structure -any item in the array can be accessed instantly -EXAMPLE -to access item 23 in an array, simply take the address of the beginning of the array and add 23 times the size of each item -address of arr[23] is address of arr[0]+(23*4) -no matter the size of the array, accessing item i can be done in O(c) -ie. one addition and one multiplication 24

-each time you call new, the allocated block can be anywhere in memory Circle c1 = new Circle(); Circle c2 = new Circle(); -c1 may be at location 2048, and c2 may be at location 640 -you have no control over this! 25

linked structures 26

-linked structures are data storage in which individual items have links (references) to other items -items don t reside in a single contiguous block of memory -items can be dynamically added or removed from the structure, simply by creating or destroying links item 2 item 1 item 3 how is this different than an array? 27

-linked structures have a reference to another instance of the structure -looks a bit like a recursive class definition class LinkedNode { //each node stores some data int ID; String name; } LinkedNode next; //and one of itself! 28

-nodes could also have multiple links -think of a family tree, or airports class LinkedNode { //each node stores some data int ID; String name; } ArrayList<LinkedNode> neighbors; 29

linked lists 30

-we ve seen a list implemented with an array in ArrayList<> -a linked list is another way to implement a list -each node, or item in the list, has a link to the next item in the list value ref value ref value ref -a single node consists of some data and a reference to another node 31

nodes may not be contiguous in memory! 6 8 4 1 2 32

-with an array, we have a single variable that can access any item with [] -with a linked list, how do we access individual elements? -HINT: we need somewhere to start -always keep track of the first node -called the head -from the head node we can access any other node by following the links 33

6 8 4 head 1 2 34

LinkedNode head = new LinkedNode(); head.id = 5; head.name = head node ; head.next = new LinkedNode(); LinkedNode temp = head.next; temp.id = 12; temp.name = next node ; head node 5 next node 12 35

linked list vs array -cost of accessing a random item at location i? -cost of removefirst()? -cost of addfirst()? A) c B) log N C) N D) N log N E) N 2 F) N 3 36

insertion & deletion 37

inserting into an array: 5 9 12 17 25 8 5 8 9 12 17 25 what is the cost of insertion? A) c B) log N C) N D) N log N E) N 2 F) N 3 inserting into a linked list: 5 9 12 17 25 8 5 9 12 17 25 8 38

deletion from a linked list: 5 9 12 17 25 5 9 12 17 25 9 is now stranded garbage collector will clean it up 39

implementation details 40

-linked lists have some methods, a size, etc. -but, it doesn t make sense for every node to store the size! -out class LinkedList keeps track of the size, head node, and defines all methods -Node should be a simple, inner class (private) -with a data field, and one or more Nodes (links) 41

nongeneric implementation (only stores ints): class LinkedList { private Node head; private int size; } private class Node { private int data; private Node next; } 42

things to consider -what should next be for the last item in the list? -don t let a call to new LinkedNode() cause an infinite loop -ie. creating a new LinkedNode, which creates a new LinkedNode, and so on -constructor should set next to null 43

traversing a linked list: public boolean contains(int item) { Node temp = head; while(temp!= null) { if(temp.data == item) return true; } temp = temp.next; } return false; 44

exercise -what is the implementation of get()? public int get(int i) { } -NOTES -throws NoSuchElementException if i is out of range -move the next node with the.next reference -what is the equivalent method for an ArrayList? 45

doubly-linked lists 46

-nodes have a link to next and previous node -allows for traversal in either forward or reverse order -maintains a tail node as well as a head node -why? -how can we use a doubly-linked list to optimize get(i)? 47

-special cases (empty or single-item lists) are more tricky due to managing tail as well as head -what are the values of head and tail for any empty list? -what about for a single-item list? 48

doubly-linked list insertion: newnode = new Node<Character>(); newnode.data = n ; newnode.prev = current; newnode.next = current.next; newnode.prev.next = newnode; newnode.next.prev = newnode; head a current c k o y tail n 49

doubly-linked list deletion: current.prev.next = current.next; current.next.prev = current.prev; head a current c k o y tail n 50

generic implementation: class LinkedList<E> { private Node head; private Node tail; private int size; } private class Node { private E data; private Node next; private Node prev; } 51

things to consider -adding to the front or end of a linked list is a little different than adding somewhere in the middle -why? -removing from a list with 1 node -what happens to head/tail? -adding to an empty list -what is the current value of head/tail? 52

LinkedList vs ArrayList 53

LinkedList vs ArrayList insertion & deletion: (assuming position is known) O(c) O(N) accessing a random item: O(N) O(c) -choose the structure based on the expected use -what is the common case? -what if insertion / deletion is always from the front / end? 54

next time 55

-reading -chapter 16 -chapter 2 -http://opendatastructures.org/ods-java/ -homework -assignment 5 due tonight -assignment 6 is out 56