Sorting & Searching (and a Tower)

Similar documents
Sorting and Searching -- Introduction

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

Sorting and Searching

12/1/2016. Sorting. Savitch Chapter 7.4. Why sort. Easier to search (binary search) Sorting used as a step in many algorithms

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L

We can use a max-heap to sort data.

Searching and Sorting (Savitch, Chapter 7.4)

SORTING. Comparison of Quadratic Sorts

What is an algorithm?

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Sorting. Order in the court! sorting 1

Sorting. Order in the court! sorting 1

Introduction. Sorting. Table of Contents

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 Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace

algorithm evaluation Performance

Introduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting.

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Overview of Sorting Algorithms

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

Unit-2 Divide and conquer 2016

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

SAMPLE OF THE STUDY MATERIAL PART OF CHAPTER 6. Sorting Algorithms

Searching and Sorting

1 a = [ 5, 1, 6, 2, 4, 3 ] 4 f o r j i n r a n g e ( i + 1, l e n ( a ) 1) : 3 min = i

Recursion. Thinking Recursively. Tracing the Recursive Definition of List. CMPT 126: Lecture 10. Recursion

Sorting Pearson Education, Inc. All rights reserved.

Sum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?

! 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.

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion. ! When the initial copy finishes executing, it returns to the part of the program that made the initial call to the function.

O(n): printing a list of n items to the screen, looking at each item once.

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Homework Assignment #3. 1 (5 pts) Demonstrate how mergesort works when sorting the following list of numbers:

Sorting and Searching Algorithms

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

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

Analysis of Algorithm. Chapter 2

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.

Searching and Sorting

Cpt S 122 Data Structures. Sorting

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

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

Programming II (CS300)

CSE 2123 Sorting. Jeremy Morris

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

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

UNIT 5C Merge Sort. Course Announcements

Computational Complexity: Measuring the Efficiency of Algorithms

1.7 Recursion. Department of CSE

Recursive Definitions

Sorting is a problem for which we can prove a non-trivial lower bound.

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

BM267 - Introduction to Data Structures

CS61B, Spring 2003 Discussion #15 Amir Kamil UC Berkeley 4/28/03

Introduction. two of the most fundamental concepts in computer science are, given an array of values:

Programming II (CS300)

Instructions PLEASE READ (notice bold and underlined phrases)

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

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

C/C++ Programming Lecture 18 Name:

Lecture 19 Sorting Goodrich, Tamassia

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Lecture 24 Tao Wang 1

Computer Science 4U Unit 1. Programming Concepts and Skills Algorithms

Chapter 3:- Divide and Conquer. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

Sorting and Searching

IS 709/809: Computational Methods in IS Research. Algorithm Analysis (Sorting)

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

Sorting/Searching and File I/O

L14 Quicksort and Performance Optimization

Table ADT and Sorting. Algorithm topics continuing (or reviewing?) CS 24 curriculum

Sorting is ordering a list of objects. Here are some sorting algorithms

Solving problems by recursion

QuickSort. CIS 15 : Spring 2007

UNIT 7. SEARCH, SORT AND MERGE

CS 171: Introduction to Computer Science II. Quicksort

Building Java Programs Chapter 13

Sorting Algorithms. + Analysis of the Sorting Algorithms

ITEC2620 Introduction to Data Structures

C22a: Problem Solving using Recursion

26 How Many Times Must a White Dove Sail...

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem

Algorithm Analysis. CENG 707 Data Structures and Algorithms

! 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.

Measuring algorithm efficiency

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

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

q To develop recursive methods for recursive mathematical functions ( ).

Divide & Conquer. 2. Conquer the sub-problems by solving them recursively. 1. Divide the problem into number of sub-problems

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

q To develop recursive methods for recursive mathematical functions ( ).

Merge- and Quick Sort

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 27, 2013

Recursive Sequences. Lecture 24 Section 5.6. Robb T. Koether. Hampden-Sydney College. Wed, Feb 26, 2014

Transcription:

Sorting & Searching (and a Tower) Sorting Sorting is the process of arranging a list of items into a particular order There must be some value on which the order is based There are many algorithms for sorting a list of items These algorithms vary in efficiency We will examine three specific algorithms: Selection Sort, Insertion Sort, and Quick Sort Selection Sort The approach of Selection Sort: select one value and put it in its final place in the sort list repeat for all other values An expanded version: scan the list to find the smallest value put it in the first position find the next smallest value put it in the second position repeat until all values are placed

Selection Sort (cont.) An example: original: 3 9 6 1 2 smallest is 1: 1 9 6 3 2 smallest is 2: 1 2 6 3 9 smallest is 3: 1 2 3 6 9 smallest is 6: 1 2 3 6 9 public static void doselectionsort (int[] numbers) int min; int temp; for (int index = 0; index < numbers.length - 1; index++) min = index; for (int scan = index + 1; scan < numbers.length; scan++) if (numbers[scan] < numbers[min]) min = scan; // swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; } // end for } // method doselectionsort

Insertion Sort The approach of Insertion Sort: Pick any item and insert it into its proper place in a sorted sublist repeat until all items have been inserted An expanded version: consider the first item to be a sorted sublist (of one item) insert the second item into the sorted sublist, shifting items as necessary to make room to insert the new addition insert the third item into the sorted sublist (of two items), shifting as necessary repeat until all values are inserted into their proper position An example: original: 3 9 6 1 2 insert 9: 3 9 6 1 2 insert 6: 3 6 9 1 2 insert 1: 1 3 6 9 2 insert 2: 1 2 3 6 9 public static void doinsertionsort (int[] numbers) for (int index = 1; index < numbers.length; index++) int key = numbers[index]; int position = index; // shift larger values to the right while (position > 0 && numbers[position-1] > key) numbers[position] = numbers[position-1]; position--; } // end while numbers[position] = key; } // end for } // method doinsertionsort

Quick Sort More efficient sort using recursion. Can also be iterative (can you figure out how?) Strategy: Divide into 2 halves according to arbitrary index value left lower than index value right greater than index value Apply strategy to each division recursively until all items sorted public void doquicksort (int[] numbers, int start, int end) if (start < end) int pivot = partition(numbers, start, end); doquicksort (start, pivot - 1); doquicksort (pivot + 1, end); } // end if } // method doquicksort private int partition (int[] numbers, int start, int end) int pivotvalue = numbers[start]; int pivotindex = start; int temp; for (int index = start + 1; index <= end; index++) if (numbers[index] < pivotvalue) pivotindex++; temp = numbers[pivotindex]; numbers[pivotindex] = numbers[index]; numbers[index] = temp; } // end if } // end for // switch pivot value into proper position temp = numbers[start]; numbers[start] = numbers[pivotindex]; numbers[pivotindex] = temp; return pivotindex; } // method partition

Comparing Sorts Both Selection and Insertion Sorts are similar in efficiency The both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list That is approximately n 2 number of comparisons for a list of size n We therefore say that these sorts are of order n 2 Quick Sort is (can be) more efficient: order n log 2 n Orders of Magnitude (lowest to highest most efficent to least efficient) O(1) - Constant O(log 2 n) - Logarithmic O(n) - Linear O(n log 2 n) - N log N O(n 2 ) - Quadratic O(n 3 ) - Cubic O(a n ) - Exponential O(n!) - Factorial Input Size 1 2 4 8 16 32 64 O(1) 1 1 1 1 1 1 1 O(log n) 2 0 1 2 3 4 5 6 O(n) 1 2 4 8 16 32 64 O(n log n) 2 0 2 8 24 64 160 384 O(n 2 ) 1 4 16 64 256 1024 4096 O(n 3 ) 1 8 64 512 4096 32768 2.6x10 5 O(2 n ) 2 4 16 256 65536 4294967296 1.85x10 19 O(n!) 1 2 24 40320 2.09x10 13 2.63x10 35 1.27x10 89

Towers of Hanoi The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top The goal is to move all of the disks from one peg to another under the following rules: o We can move only one disk at a time o We cannot move a larger disk on top of a smaller one o Move the stack of disks from the starting peg to one of the other pegs, moving only one disk at a time, and without placing a larger disk on top of a smaller disk. The Towers of Hanoi problem is of exponential complexity!! (2 n - 1)

Towers of Hanoi Manual Solution Towers of Hanoi Programmed Recursively int totaldisks = 5; movetower (totaldisks, 1, 3, 2); public void movetower (int numdisks, int start, int end, int temp) if (numdisks == 1) moveonedisk (start, end); movetower (numdisks - 1, start, temp, end); moveonedisk (start, end); movetower (numdisks - 1, temp, end, start); } } private void moveonedisk (int start, int end) System.out.println ("Move one disk from " + start + " to " + end); } Towers of Hanoi Animated

Searching The goal is to find a particular target value In an unsorted list, a linear search is a simple technique Scan through the list one item at a time in order looking for the target value If the list is sorted, not all items need to be examined As soon as you encounter a value greater than the target value, you know the target is not in the list Iterative Binary Search If the list is sorted, we can use a binary search to find the target value Strategy: Examine the item in the middle of the list, eliminating half of the items from consideration The target value will either be found, or will be in one half or the other Continue the process, examining the middle item of the search section on each comparison public static int iterativebinarysearch (int[] numbers, int target) int index; int left = 0 int right = numbers.length - 1; int retval = -1; // assume target not found while (left <= right) index = (left + right) / 2; if (target == numbers[index]) retval = index; // target found if (target > numbers[index]) left = index + 1; right = index - 1; } return retval; } // method iterativebinarysearch

Recursive Binary Search The binary search algorithm can be implemented recursively It has the same general strategy as the iterative version Each recursive call narrows the search section private int recursivebinarysearch (int[] numbers, int target, int left, int right) int retval; // return value int index = (left + right) / 2; if (left > right) // target not found retval = -1; if (target == numbers[index]) // target found retval = index; if (target > numbers[index]) retval = recursivebinarysearch (numbers, target, index + 1, right); retval = recursivebinarysearch (numbers, target, left, index - 1); return retval; } // method recursivebinarysearch