Search,Sort,Recursion.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
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.
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.
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.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
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
Chapter 9: Sorting and Searching Arrays
Searching and Sorting Algorithms
Recursion Version 1.0.
Searching and Sorting Arrays
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 9: Searching, Sorting, and Algorithm Analysis
Recitation 13 Searching and Sorting.
CSC 421: Algorithm Design & Analysis
Teach A level Computing: Algorithms and Data Structures
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
Searching and Sorting Topics Sequential Search on an Unordered File
Introduction to Programming
Searching and Sorting Topics Sequential Search on an Unordered File
Searching and Sorting Arrays
MSIS 655 Advanced Business Applications Programming
Searching and Sorting 1-D Arrays
UMBC CMSC 104 – Section 01, Fall 2016
Search,Sort,Recursion.
Searching and Sorting Topics Sequential Search on an Unordered File
24 Searching and Sorting.
Basics of Recursion Programming with 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
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CSCE 3110 Data Structures & Algorithm Analysis
CSC 421: Algorithm Design & Analysis
CHAPTER 9 SORTING & SEARCHING.
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

Search,Sort,Recursion

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 known as the target or key Algorithm Look at each element from first to last to see if the target value is equal to any of the array elements Return the index of the target value to indicate where the target was found in the array Return a value of -1 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.

Search – two implementations int search(int array[], int size, int target) { int index = 0; bool found = false; while ((!found) && (index < size)) { if (target == array[index]) found = true; else index++; } if (found) return index; else return -1; int search(int array[], int size, int target) { for(int index = 0;index < size; index++) if (target == array[index]) return index; } return -1;

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_index = start; for (int i = start+1; i < num_used; i++) if (array[i] < array[min_index]) min_index = i; return min_index; }

BubbleSort Goal: order the array from smallest to largest Loop through the entries If the current value is greater than the next one, swap them If ANY swaps happened, need to loop through all over again!

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.

Sort – by Hand RandArray 46 48 29 69 81 19 26 77 14 85 2 SortedArray index 1 3 4 5 6 7 8 9 10 11 SortedArray  

Lab 11: Bubble Sort void bubbleSort(int A[],int arraySize) { bool did1swap; // indicates that we need to go through again do { did1swap = false; // go through all elements, compare each item & the one higher for (int i = 0; i < arraySize - 1; i++) //stop before the top if (A[i] > A[i + 1]) { // if one is out of order, then swap(A[i], A[i + 1]); // swap them did1swap = true;// need another run } } while (did1swap == true);

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

Recursion When a function calls itself: Can be a simpler way to write a loop Can be used as a 'divide-and-conquer' method

Power calculation, another way to look at it 2 5 = 2 * 2 * 2 * 2 * 2 We can also say 2 5 = 2 * 2 4 And we know: 2 0 = 1

Alternate power (pow) function 𝑏𝑎𝑠𝑒 𝑒𝑥𝑝 int power(int base, int expon) { if(expon>0) return (base * power(base,expon-1)); else return 1; // any base with 0 as exponent = 1 } Recursive case Stop (base) case

Recursive function design Must have: Stopping case, sometimes called 'base case' Simplified recursive calls – each new call must bring us closer to reaching base case(s) – these are the ‘recursive cases’.

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. At least one recursive case that breaks the problem into smaller piece At least one base case that stops the recursion. 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 t leomework is recursive Factorial and Fibonacci are naturally recursive as are tree searches. Recursion is extremely inefficient. Only use it if you must.