Search,Sort,Recursion.

Slides:



Advertisements
Similar presentations
CSE Lecture 3 – Algorithms I
Advertisements

Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
CS 1400 March 30, 2007 Chapter 8 Searching and Sorting.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Searching Arrays Linear search Binary search small arrays
Searching and Sorting Arrays
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 8 ARRAYS Continued
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.
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
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.
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.
CSC 211 Data Structures Lecture 13
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
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.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
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.
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.
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.
Data Structures Arrays and Lists Part 2 More List Operations.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
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 Arrays Linear search Binary search small arrays
Searching and Sorting Arrays
16 Searching and Sorting.
Searching and Sorting Algorithms
Chapter 15 Recursion.
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
Searching Given a collection and an element (key) to find… Output
Introduction to Search Algorithms
Chapter 15 Recursion.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Recitation 13 Searching and Sorting.
CSC 421: Algorithm Design & Analysis
Teach A level Computing: Algorithms and Data Structures
Arrays … The Sequel Applications and Extensions
Searching and Sorting Linear Search Binary Search ; Reading p
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.
Algorithm design and Analysis
Introduction to Search Algorithms
CSc 110, Spring 2017 Lecture 39: searching.
Chapter 8 Search and Sort
Searching and Sorting Arrays
MSIS 655 Advanced Business Applications Programming
Standard Version of Starting Out with C++, 4th Edition
24 Searching and Sorting.
Search,Sort,Recursion.
CSC 421: Algorithm Design & Analysis
Searching and Sorting Arrays
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Principles of Computing – UFCFA3-30-1
CSCE 3110 Data Structures & Algorithm Analysis
CHAPTER 9 SORTING & SEARCHING.
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

Search,Sort,Recursion

Let’s submit it!

Searching, Sorting and Recursion Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search

Searching Arrays A sequential search is one way to search an array for a given value Look at each element from first to last to see if the target value is equal to any of the array elements The index of the target value can be returned to indicate where the value was found in the array A value of -1 can be returned if the value was not found

The search Function The search function of Display 7.10… Uses a while loop to compare array elements to the target value Sets a variable of type bool to true if the target value is found, ending the loop Checks the boolean variable when the loop ends to see if the target value was found Returns the index of the target value if found, otherwise returns -1

Linear Search Let’s try this example: int array[8] = { 6, 4, 1, 9, 7, 3, 2, 8 }; Let’s say we have to find value 3 in the array, how do we use a linear search for this? Compare each element with the target value 3. If any element of the array matches, return the index of the element. If no element of the array matches, return -1.

Pseudocode for Linear Search For each element in the list do If the current element is the same as the target, return the index of the current element If the entire list was searched and the target wasn’t found, return -1 .What is the worst case scenario? Need to search all a[0]..a[n] elements before target is not found. What is the best case scenario? Need to search only a[0] before target is found.

Exercise Write a program that will read up to 10 letters into an array and write the letters back to the screen in the reverse order? abcd should be output as dcba Use a period as a sentinel value to mark the end of input

Inserting into an array Arrays are great for keeping unordered lists of values. But what if you want an ordered list of values? You can sort the values in an array using a sort function. Or you can place them into the array in sorted order. If you want to place them in sorted order, you need to be able to insert a new value in the correct position. Let’s assume you know how to find the position for insertion.

Inserting into an Array Recall that an array is just a collection that is kept in sequential memory. int array[20] = { 1, 3, 6, 7, 10 }; Recall that an initializer that specifies fewer values than the array capacity initializes the remaining cells to 0 of the base type. Let’s say we want to insert the value 4 in the 3rd position without losing the values larger than 4. What do we have to do?

We have to make room for the new value by pushing the other values down 1 position. As long as there is CAPACITY, we can start at the end and move the contents down 1. We do that in a loop that starts at the end and goes back towards the insertion position.

Pseudocode - Insert a value into an Array Is there enough room for another value? Test if increasing Number Of Elements by 1 will be greater than the Capacity. If the array is full, fail gracefully. That will depend on the return type. Failing gracefully: If the return type is void, just return and do nothing. If the return type is bool, return false. If the return type is int, return -1. For each element starting from the last element (i.e. number of elements – 1) until we reach the insert position, do array[i+1] = array[i] Increase the size of number of elements by 1.

Deleting an element from an Array Check that the position given for deletion is within the valid range. What is the valid range? The valid range is from 0 to number of elements – 1. If the position is not in range, fail gracefully. For each element starting from the index of the delete position, do array[i] = array[i+1] Decrease the size of number of elements.

Program Example: Sorting an Array Sorting a list of values is very common task Create an alphabetical listing Create a list of values in ascending order Create a list of values in descending order We already saw Selection sort Recall that for each position, traverse the rest of the array to find the minimum value and swap it with the current value. Many sorting algorithms exist Some are very efficient Some are easier to understand

Program Example: The Selection Sort Algorithm When the sort is complete, the elements of the array are ordered such that a[0] < a[1] < … < a [ number_used -1] Outline of the algorithm for (int index = 0; index < number_used; index++) place the index-th smallest element in a[index]

Program Example: Sort Algorithm Development One array is sufficient to do our sorting Search for the smallest value in the array Place this value in a[0], and place the value that was in a[0] in the location where the smallest was found Starting at a[1], find the smallest remaining value swap it with the value currently in a[1] Starting at a[2], continue the process until the array is sorted Display 7.11 Display 7.12 (1-2)

Display 7.11

Selection sort Remember the Outline of the algorithm for (int index = 0; index < number_used; index++) place the index-th smallest element in a[index]; Write a function to return the index of the smallest int index_of_min(int array[], int num_used, int start) { int min = array[start]; for (int i = start+1; i < num_used; i++) if (array[i] < min) min = array[i]; return min; }

Bubble Sort Another algorithm for sorting arrays. Compare each pair of adjacent array elements, if they are in the wrong order, swap them. Continue until the array is sorted. Bubble sort is named for what happens with soda. The light bubbles float to the top, the heavy soda floats to the bottom.

Bubble Sort Performance How many times does a bubble sort traverse the array? Standard Bubble sort always takes O(N*N) time for an array of size N. Bubble sort is not efficient, it is easy to implement and understand. How can bubble sort be made a little more efficient? Stop sorting if a pass makes no swaps.

Binary Search Algorithm int binary_search(int array[], int size, int search) { // array is sorted in ascending order int first = 0; int last = size-1; int middle = (last+first)/2; // divide the array into two parts while (first <= last) { if (array[middle] < search) // it’s in the bigger half { first = middle + 1; } else if (array[middle] == search) return middle; // found it else // it’s in the smaller half. last = middle - 1; middle = (last+first)/2; // divide the array into two parts return -1; Binary Search Algorithm

Recursive Binary Search int binary_search(int array[], int first, int last, int search) {// array is sorted in ascending order int middle = (last+first)/2; // divide the array into two parts if (first <= last) { if (array[middle] < search) { // it’s in the bigger half return binary_search(array, middle+1, last, search); } else if (array[middle] == search) { return middle; else { return binary_search(array, first, middle-1, search); } else { return -1;

Recursion A problem that can be solved by dividing it into smaller and smaller ‘like’ pieces. In Computer Science, a recursive function is a function that calls itself until it gets to a boundary case and then completes the computation as it unwinds. Examples of recursive problems: The factor function from the homework is recursive Factorial and Fibonacci are naturally recursive as are tree searches. Recursion is extremely inefficient. Only use it if you must.