12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 ©1995-2000 Barnette ND, McQuain WD, Keenan MA 1 Simple Searching Many.

Slides:



Advertisements
Similar presentations
Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Advertisements

Searching for Data Relationship between searching and sorting Simple linear searching Linear searching of sorted data Searching for string or numeric data.
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.
CSE Lecture 3 – Algorithms I
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 9: Searching, Sorting, and Algorithm Analysis
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Sorting and Searching. Searching List of numbers (5, 9, 2, 6, 3, 4, 8) Find 3 and tell me where it was.
CHAPTER 11 Sorting.
C++ Plus Data Structures
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Chapter 8 ARRAYS Continued
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
CSC 211 Data Structures Lecture 13
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Sorting Many computer applications.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
CSCI 51 Introduction to Programming March 12, 2009.
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.
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
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.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
1 Principles of Computer Science I Honors Section Note Set 5 CSE 1341.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
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.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
CS 162 Intro to Programming II Sorting Introduction & Selection Sort 1.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
 Introduction to Search Algorithms  Linear Search  Binary Search 9-2.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Searching and Sorting Searching algorithms with simple arrays
Searching and Sorting Arrays
Chapter 9: Sorting and Searching Arrays
Introduction to Search Algorithms
Topic 14 Searching and Simple Sorts
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Binary Search Back in the days when phone numbers weren’t stored in cell phones, you might have actually had to look them up in a phonebook. How did you.
CSc 110, Spring 2017 Lecture 39: searching.
Searching and Sorting Arrays
Searching and Sorting 1-D Arrays
Searching CLRS, Sections 9.1 – 9.3.
Topic 14 Searching and Simple Sorts
Searching and Sorting Arrays
CS 1044 Intro Programming in C++ Fall 2002
Searching and Sorting Arrays
Presentation transcript:

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 1 Simple Searching Many computer applications involve searching for particular data that has been previously stored. Problem: Find the position of an element, Target, in an array of integers: int List[Size]; Cannot assume that Target is in the list. If Target does not exist in List[] then return -1 (an impossible location).

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 2 const int MISSING = -1 ; int LinearSearch(const int List[], int Target, int Size) { int Scan = 0; // begin search at first cell // Continue searching while there are more entries // to consider and the target value has not beeen // found: while ( ( Scan < Size ) && (List[Scan] != Target) ) Scan++ ; if ( Scan < Size ) // Target was found return( Scan ); else return ( MISSING ); // Target was not found } Linear Searching Simply scan the list until Target is found or the end of the list is reached.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 3 Binary Search Assumption: the list is sorted in ascending (or descending) order: List[0] <= List[1] <=... <= List[size-1] Examine the middle element. If the desired element is not found, determine to which side it falls. Divide that section in half and examine the middle element, etc, etc... ? ? ? ? ? x y z

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 4 Binary Search Code const int MISSING = -1 ; int BinSearch(const int List[], int Target, int Lo, int Hi ) { int Mid; while ( Lo <= Hi ) { Mid = ( Lo + Hi ) / 2; // locate middle if ( List[Mid] == Target ) // check for target return ( Mid ); else if ( Target < List[Mid] ) Hi = Mid - 1; // look in lower half else Lo = Mid + 1; // look in upper half } return ( MISSING ); // Target not found } assert ( (Lo > 0) && (Lo < MAX_ARRAY_SIZE) && (Hi > 0) && (Hi < MAX_ARRAY_SIZE)) ; // no need to assert( Lo <= Hi ) ;

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 5 Binary Search Trace Suppose the array contained the following values: Find the position of 110. Lo Hi Mid 0 7 the call bin_search ( a, 110, 0, 7 ) returns -> Find the position of 38. Lo Hi Mid 0 7 the call bin_search ( a, 38, 0, 7 ) returns ->

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 6 Cost of Searching Suppose the array to be searched contains N elements. The cost of searching may be measured by the number of array elements that must be compared to xelem. Using that measure: Best CaseWorst CaseAverage Case Linear Search1NN/2 Binary Search1log 2 N log 2 N To get an idea of how much cheaper binary search is, note that N = 1024 log 2 N = 10 N = log 2 N = 20 Of course, binary search is only feasible if the array is sorted...

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 7 Sorting Many computer applications involve sorting items into some specified order. To sort a group of items, the following relationships must be clearly defined over the items to be sorted: One goal of sorting is to minimize the number of comparisons necessary to sort the list of items. Ascending Order: low... high, first... last Descending Order: high... low, last... first a<ba>ba=ba<ba>ba=b

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 8 Decision Trees To sort three items (a, b, c), how many comparisons must be made? The decision tree above assumes that the three items (a, b, c), are unique.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 9 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 to be exchanged with another to reach its correct position. 2.1 Loop (i) from 0 to size of the list to be sorted Compare the i th & i th + 1 elements in the unsorted list Swap the i th & i th + 1 elements if not in order ( ascending or descending as desired) Adjacent array locations are compared and swapped until the array is sorted

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 10 Bubble Sort Code void BubbleSort(int List[], const int Size) { void Swap( int& elem1, int& elem2); for (int Stop = Size - 1; Stop > 0; Stop--) { for (int Check = 0; Check < Stop; Check++) { if (List[Check] > List[Check + 1]) Swap(List[Check], List[Check + 1]); } void Swap(int& elem1, int& elem2) { int temp = elem1; elem1 = elem2; elem2 = temp; } void BubbleSort(int List[], const int Size) { void Swap( int& elem1, int& elem2); for (int Stop = Size - 1; Stop > 0; Stop--) { for (int Check = 0; Check < Stop; Check++) { if (List[Check] > List[Check + 1]) Swap(List[Check], List[Check + 1]); } void Swap(int& elem1, int& elem2) { int temp = elem1; elem1 = elem2; elem2 = temp; } This can be improved by modifying the outer loop to exit if the list is already sorted.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 11 Bubble Sort Trace <- indices Original array First Pass First Pass First Pass Second Pass Second Pass Third Pass Third Pass Fourth Pass Fifth Pass Characteristics:Compares adjacent elements.Simple, but not very efficient.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 12 Selection Sort Algorithm 1. Loop (i) from 0 to the (number of elements to be sorted - 2) 1.1 Assume the smallest remaining item is at the i th position, call this location smallest. 1.2 Loop (j) through the remainder of the list to be sorted (i+1.. size-1) Compare the j th & smallest elements in the unsorted list If the j th element is < the smallest element then reset the location of the smallest to the j th location. 1.3 Move the smallest element to the head of the unsorted list, (i.e. swap the ith and smallest elements). After sorting all but 1 element the remaining element must be in its correct position.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 13 Straight Selection Sort void SelectionSort(int List[], const int Size) { int Begin, SmallSoFar, Check; void Swap(int& elem1, int& elem2);// see previous slide for (Begin = 0; Begin < Size - 1; Begin++) { SmallSoFar = Begin; // set head of tail for (Check = Begin + 1; Check < Size; Check++) { // scan current tail if (List[Check] < List[SmallSoFar]) SmallSoFar = Check; } Swap(List[Begin], List[SmallSoFar]); } void SelectionSort(int List[], const int Size) { int Begin, SmallSoFar, Check; void Swap(int& elem1, int& elem2);// see previous slide for (Begin = 0; Begin < Size - 1; Begin++) { SmallSoFar = Begin; // set head of tail for (Check = Begin + 1; Check < Size; Check++) { // scan current tail if (List[Check] < List[SmallSoFar]) SmallSoFar = Check; } Swap(List[Begin], List[SmallSoFar]); } Assumes the entire list from 0.. Size-1 is to be sorted. Parameters ( first, last ) would be required to allow a subset of the list to be sorted.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 14 Selection Sort Trace <- indices Original array First Pass Second Pass Third Pass Characteristics:Every pass places one more element in its final sorted position. Performs approximately the same number of comparisons as bubble sort. Performs many fewer swaps than bubble sort.

12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 15 Cost of Sorting Suppose the array to be sorted contains N elements. The cost of sorting may be measured by the number of array elements that must be compared to each other, or by the number of times two array elements must be swapped. Using those measures (approximately): ComparisonsSwaps WorstAverageWorstAverage Bubble SortN 2 N 2 N 2 N 2 Selection Sort N 2 N 2 N-1N-1 In some cases, comparisons are more expensive than swaps; in other cases, swaps may be more expensive than comparisons. In any case, there is no cost advantage to using Bubble Sort. There are other, more complex, sorting algorithms whose costs are on the order of Nlog 2 N — those are introduced in CS 1704.