The Linear and Binary Search and more Lecture Notes 9.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
Chapter 4: Divide and Conquer Master Theorem, Mergesort, Quicksort, Binary Search, Binary Trees The Design and Analysis of Algorithms.
DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
Data Structures Data Structures Topic #13. Today’s Agenda Sorting Algorithms: Recursive –mergesort –quicksort As we learn about each sorting algorithm,
Data Structures and Algorithms PLSD210 Sorting. Card players all know how to sort … First card is already sorted With all the rest, ¶Scan back from the.
Chapter 19: Searching and Sorting Algorithms
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
CHAPTER 11 Sorting.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 20: Sorting.
Algorithm Efficiency and Sorting
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
Lecture 08 Sorting. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. – We first looked at.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
Computer Algorithms Lecture 10 Quicksort Ch. 7 Some of these slides are courtesy of D. Plaisted et al, UNC and M. Nicolescu, UNR.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
Chapter 19: Searching and Sorting Algorithms
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
Computer Science Searching & Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
CSC 211 Data Structures Lecture 13
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Data Structure Introduction.
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
Sort Algorithms.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
1 CSE 373 Sorting 3: Merge Sort, Quick Sort reading: Weiss Ch. 7 slides created by Marty Stepp
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Chapter 9 Sorting 1. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
The Sorting Methods Lecture Notes 10. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. –
Sorting Fundamental Data Structures and Algorithms Aleks Nanevski February 17, 2004.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Quicksort Quicksort is a well-known sorting algorithm that, in the worst case, it makes Θ(n 2 ) comparisons. Typically, quicksort is significantly faster.
QuickSort. Yet another sorting algorithm! Usually faster than other algorithms on average, although worst-case is O(n 2 ) Divide-and-conquer: –Divide:
Basic Sorting Algorithms Dr. Yingwu Zhu. Sorting Problem Consider list x 1, x 2, x 3, … x n Goal: arrange the elements of the list in order Ascending.
329 3/30/98 CSE 143 Searching and Sorting [Sections 12.4, ]
WHICH SEARCH OR SORT IS BETTER?. COMPARING ALGORITHMS Time efficiency refers to how long it takes an algorithm to run Space efficiency refers to the amount.
Searching and Sorting Searching algorithms with simple arrays
Chapter 7 Sorting Spring 14
Data Structures and Algorithms
Description Given a linear collection of items x1, x2, x3,….,xn
CO 303 Algorithm Analysis And Design Quicksort
Sub-Quadratic Sorting Algorithms
slides adapted from Marty Stepp
EE 312 Software Design and Implementation I
CSE 373 Data Structures and Algorithms
Data Structures & Algorithms
Searching.
Presentation transcript:

The Linear and Binary Search and more Lecture Notes 9

Linear Search Suppose we have a vector of ints How do we search for a target Write the code to do this Analyze your code Is it working under all conditions? Have you tested all possible inputs?

Linear Search Algorithm Public int linearSearch(int target){ for (int I=0;I<A.size();I++) if (A.elementAt(I)==target) return i; return -1; }

Linear Search -analysis Worst case is target item not in the list or at the end – N comparisons – Order(n) Best case is target is at the first position – Order(1) complexity Average case – (n+(n-1)+(n-2)+…+1)/n comparisons – Average complexity is order(n)

Binary Search Linear Search is highly time consuming for arrays(vectors) that are large So what if the array is sorted? Is there a better way to do the search Answer: yes Look at the middle element – If the target is smaller, look to the left sub-array – If the target is larger, look to the right sub-array

Binary Search ctd.. Consider The middle element is (n+1)/2 If the target is 15, then – Search left – Else search right Write the code Analyze the algorithm

Binary Search Algorithm public int binarySearch(Object target){ int first=0, last=A.size()-1; while (first<=last){ middle=(first+last)/2; if (A.elementAt(middle) > target) {last=middle-1;} else if (A.elementAt(middle) < target) {first=middle+1;} else return middle; } return -1 }

Analysis of the binary Search

Other Search Algorithms Breadth-first search is one of the two most common search algorithms The approach of breadth-first search is to start with a queue containing a list of nodes to visit A node is a state or a value; in programming it is usually represented as a structure containing particular information about the environment or domain of the problem.

Other Search Algorithms ctd.. The algorithm starts by placing the initial state of the problem into the head (beginning) of the queue The search then proceeds by visiting the first node and adding all nodes connected to that node to the queue The search then proceeds by visiting the first node and adding all nodes connected to that node to the queue. When viewed as a tree graph, it would move from left to right from the current node (usually represented as a circle on a graph) along links (represented as connecting lines in between the node circles) to connected nodes, adding the connected nodes to the queue. As the head node of the queue is visited it is removed. The search then moves to the next node on the queue and continues until the goal is reached.

Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. – We first looked at a linear search it doesn’t care whether the data is sorted or not the algorithm starts at the first element in the vector, and looks at every element in the vector, in sequence, until it finds what it is looking for, or comes to the end of the vector – With small data sets this algorithm performs acceptably – If the data sets are of significant size, than performance can become unacceptable We have since looked at Binary Search, which improves performance, IF the data is sorted

Sorts If we know that a data set is sorted in some order (lowest to greatest, largest to smallest, highest priority to lowest priority), then we can write searches to take advantage of this fact. – If you have misplaced your calculator in the library in the afternoon, you do not have to retrace your steps from when you arrived on campus in the morning to find it – You start your search in the library – When looking up a phone number in the phone book, you do not start at page 1 and scan each page in sequence, until you find the name you are looking for

Sorting Comparison There are all kinds of sorts For our purposes a sort is a rearrangement of data into either ascending or descending order Fast Sortsversus Slow Sorts O (N log 2 N)O (N 2 ) Slow sorts are easy to code and sufficient when the amount of data is small

Bubble Sort - N 2 Sort Strategy – ‘bubble’ the smallest item to the left (slot 0) – ‘bubble’ the next smallest item to slot 1 – ‘bubble’ the third smallest item to slot 2 algorithm (for one pass) walk through the Vector if this item (in spot j) is smaller than the item in spot 0 swap item in spot j with the item in spot 0 code for (int j = 0; j < count; j++) { if (nums[j] < nums[0] { int temp = nums[j]; nums[j] = nums[0]; nums[0] = temp; }

Bubble Sort (con’t) This code for one pass finds the smallest element in the vector and puts it into slot 0 Now wrap this code in a loop that will find succeeding smaller elements and put them into the proper position in the Vector // outer for loop controls the spot that gets the appropriate smallest // value for (int left = 0; left < count - 1; left++) { // code from previous slide, with starting point being left + 1 // instead of 0, and comparing nums[j] to nums[left] for (int j = left + 1; j < count; j++) if (nums[j] < nums[left] { int temp = nums[j]; nums[j] = nums[left]; nums[left] = nums[j]; }

Selection Sort We have noticed that the most “expensive” part of the bubble sort is swapping (three lines of code to execute) A selection sort reduces the number of swaps until the end of each pass, when we know what the smallest remaining value is, and placing it appropriately Strategy – find the smallest item, and swap it with slot 0 – find the next smallest item and swap it with slot 1 – find the third smallest item and swap it with slot 2 algorithm (for one pass) walk through the Vector the first item is labeled the smallest Every other element is compared to the smallest if it is smaller, than it is labeled the smallest At the end of the walkthrough, the first is swapped with the smallest

Selection Sort (con’t) The algorithm for one pass finds the smallest element in the vector and puts it into slot 0 Now wrap this code in a loop that will find succeeding smaller elements and put them into the proper position in the Vector // outer for loop controls the spot that gets the appropriate smallest // value (same as bubble sort) for (int left = 0; left < count - 1; left++) { // last one will be correct int smallest = left;// we will keep the index to the smallest for (int j = left + 1; j < count; j++) if (nums[j] < nums[smallest] { smallest = j; } if (smallest != left) // no sense swapping if left is smallest { int temp = nums[smallest]; nums[smallest] = nums[left]; nums[left] = temp; }

Use FindSmallest() routine with SelectionSort() We have spent a lot of time looking at FindSmallest() routines… you should know how to do that Incorporate that knowledge into selection sort // outer for loop controls the spot that gets the appropriate smallest // value (same as bubble sort) for (int left = 0; left < count - 1; left++) { int smallest = findSmallest(nums, count, left); // use what we already know // pass the starting point of the // remainder of the vector to look // at if (smallest != left ) { int temp = nums[smallest]; nums[smallest] = nums[left]; nums[left] = temp; }

findSmallest(const int nums[], int count, int left); int findSmallest(const int nums[], int count, int left) { int smallest = left; // start with first index as the smallest for (int j = left + 1; j < count; j++) if (nums[j] < nums[smallest] { smallest = j; } return smallest; }

Quick Sort Most widely used algorithm Invented in 1960 by C.A.R. Hoare Not difficult to implement Good general purpose sort (works well in most cases) Average performance is n log n Reecursive (drawback) Worst case performance is n 2 (why is that????) – file already sorted time = n 2 /2 and space = n precise mathematical analysis backed up by empirical results Divide and conquer algorithm

Quick Sort Algorithm – Partitioning Step Choose a pivot element say a = v[j] Determine its final position in the sorted array – a > v[I] for all I < j – a j – Recursive Step Perform above step on left array and right array An early look at quicksort code (incomplete) void quicksort( vector &A, int left, int right) { int I; if (right > left) { Pivot(A, left, right); I = partition(A, left, right); quicksort(A, left, I-1); quicksort(A, I+1, right); }

Quick Sort Code ctd.. More Detailed look at the partition code // Partition(): rearrange A into 3 sublists, a sublist // A[left] Ö A[j-1] of values at most A[j], a sublist A[j], // and a sublist A[j+1] Ö A[right] of values at least A[j] int Partition(vector &A, int left, int right) { char pivot = A[left]; int i = left; int j = right+1; do { do ++i; while (A[i] < pivot); do --j; while (A[j] > pivot); if (i < j) { Swap(A[i], A[j]); } } while (i < j); Swap(A[j], A[left]); return j; }

Quick Sort Code ctd.. More Detailed look at the pivot code // Pivot(): prepare A for partitioning void Pivot(vector &A, int left, int right) { if (A[left] > A[right]) Swap(A[left], A[right]); } eg: trace the quick sort code for

Quick Sort Analysis Divide the file by half Recurrence relation is – C(n) = 2C(n/2) + n – 2C(n/2) is the cost of doing two partitions of size n/2 – n is the cost of examining each element Using the above recurrence relation, prove that quick sort is of n log n Let us assume that n = 2 k for some k without the loss of generality C(n)= 2C(n/2) + n = 2 (2C(n/4) + n/2) + n = 2 (2(2C(n/8)+n/4) + n/2) + n = 2 3 C(n/2 3 ) + 3 n ….. After 3 iterations So after k iterations we have C(n) = 2 k C(n/2 k ) + k. n = 2 k C(1) + k. n since n = 2 k = 2 log n. 1 + k.n = n + n log n = f(n log n) In Lab 5 you must use the recursive quicksort