Searching and Sorting

Similar documents
Analysis of Binary Search algorithm and Selection Sort algorithm

6. Standard Algorithms

For example, we have seen that a list may be searched more efficiently if it is sorted.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

CompSci-61B, Data Structures Final Exam

Binary search algorithm

Lecture Notes on Linear Search

Chapter 7: Sequential Data Structures

Pseudo code Tutorial and Exercises Teacher s Version

Data Structures and Algorithms Written Examination

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Algorithms and Data Structures Written Exam Proposed SOLUTION

Computer Science 210: Data Structures. Searching

8.1. Example: Visualizing Data

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

Zabin Visram Room CS115 CS126 Searching. Binary Search

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

AP Computer Science Java Mr. Clausen Program 9A, 9B

Searching Algorithms

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Ordered Lists and Binary Trees

Analysis of a Search Algorithm

DATA STRUCTURES USING C

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

PES Institute of Technology-BSC QUESTION BANK

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms

APP INVENTOR. Test Review

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Data Structures. Algorithm Performance and Big O Analysis

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

OPTIMAL BINARY SEARCH TREES

10CS35: Data Structures Using C

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Arrays in Java. Working with Arrays

Chapter Objectives. Chapter 9. Sequential Search. Search Algorithms. Search Algorithms. Binary Search

LINKED DATA STRUCTURES

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Binary Heap Algorithms

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Data Structures and Algorithms

Simple sorting algorithms and their complexity. Bubble sort. Complexity of bubble sort. Complexity of bubble sort. Bubble sort of lists

Basic Programming and PC Skills: Basic Programming and PC Skills:

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

Algorithms and Data Structures

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

Converting a Number from Decimal to Binary

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

COMPUTER SCIENCE (5651) Test at a Glance

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

GRID SEARCHING Novel way of Searching 2D Array

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

Curriculum Map. Discipline: Computer Science Course: C++

Introduction to Stacks

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Decision-making Computer Science Lesson to Prepare for UIL Computer Science Contest

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Introduction to Java

Solving Problems Recursively

Chapter 8: Bags and Sets

dictionary find definition word definition book index find relevant pages term list of page numbers

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Moving from CS 61A Scheme to CS 61B Java

Section IV.1: Recursive Algorithms and Recursion Trees

Query Processing C H A P T E R12. Practice Exercises

BCS2B02: OOP Concepts and Data Structures Using C++

Chapter 13: Query Processing. Basic Steps in Query Processing

Sample Questions Csci 1112 A. Bellaachia

cs2010: algorithms and data structures

Computer Programming I

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Loop Invariants and Binary Search

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Outline. Introduction Linear Search. Transpose sequential search Interpolation search Binary search Fibonacci search Other search techniques

Algorithms. Margaret M. Fleck. 18 October 2010

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

AP Computer Science AB Syllabus 1

Data Structures. Level 6 C Module Descriptor

Data Structures in the Java API

Section of DBMS Selection & Evaluation Questionnaire

Recursion vs. Iteration Eliminating Recursion

50 Computer Science MI-SG-FLD050-02

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Searching & Sorting. Contents. I. Searching 6

Transcription:

Linear Search Searching and Sorting Binary Search Selection Sort Insertion Sort Bubble (or Exchange) Sort Exercises Unit 27 1

Linear Search Searching is the process of determining whether or not a given value exists in a data structure or a storage media. We discuss two searching methods on one-dimensional arrays: linear search and binary search. The linear (or sequential) search algorithm on an array is: Sequentially scan the array, comparing each array item with the searched value. If a match is found; return the index of the matched element; otherwise return 1. The algorithm translates to the following Java method: public static int linearsearch(object[] array, Object key){ for(int k = 0; k < array.length; k++) if(array[k].equals(key)) return -1; return k; Note: linear search can be applied to both sorted and unsorted arrays. Unit 27 2

Binary Search The binary search algorithm can only be applied to an array that is sorted; furthermore, the order of sorting must be known. A recursive binary search algorithm for an array sorted in ascending order is: if(there are more elements in the current sub-array){ Compare the current middle sub-array element with key (the value searched for). There are three possibilities: 1. key == array[middle] the search is successful, return middle. 2. key < array[middle] binary search the current lower half of the array. 3. key > array[middle] binary search the current upper half of the array. if no elements left in sub-array, thus the key is not in the array; return 1 Unit 27 3

Binary Search (cont d) The algorithm translates to the following Java method : Here the objects are sorted according to the comparator, another version can be written for objects sorted based on the natural ordering public static int binarysearch(object[] array, Object key, Comparator comparator){ return binarysearch(array, key, 0, array.length - 1, comparator); private static int binarysearch(object[] array, Object key, int low, int high, Comparator comparator){ if(low > high) return -1; else{ int middle = (low + high)/2; int result = comparator.compare(key, array[middle]); if(result == 0) return middle; else if(result < 0) return binarysearch(array, key, low, middle - 1, comparator); else return binarysearch(array, key, middle + 1, high, comparator); Unit 27 4

Selection Sort Sorting is the process of arranging data in a data structure or a storage media such that it is in increasing or decreasing order for primitive types, or according to the natural ordering if the class of the sorted objects implements Comparable, or according to a comparator object that defines the criteria of sorting. We discuss five sorting algorithms on one-dimensional arrays starting with Selection Sort. The pseudo-code for Selection sort algorithm to sort an array in increasing is: selectionsort(array){ for(k = 0; k < array.length 1; k++){ select the minimum element among array[k]...array[array.length 1]; swap the selected minimum with x[k]; To sort an array in decreasing order, the maximum element is selected in each iteration (or pass) of the algorithm. Unit 27 5

Selection Sort (cont d) The algorithm translates to the following java method for Comparable objects. Another version can be written using a Comparator object as done previously in searching, or dealing with primitive types public static void selectionsort(comparable[] array ) { int minpos = 0; Object temp; for(int i = 0; i < array.length - 1; i++){ minpos = i; for(int k = i + 1; k < array.length; k++){ if(array[k].compareto(array[minpos]) < 0) minpos = k; if(i!=minpos) { temp = array[minpos]; array[minpos] = array[i]; array[i] = temp; Unit 27 6

Selection Sort (cont d) To sort an array with k elements, Selection sort requires k 1 passes. Example: Unit 27 7

Insertion Sort The array is partitioned into 2 parts, sorted (on the left) and unsorted (on the right). Initially the unsorted part has one element. In each pass, the first element of the unsorted part is inserted in the appropriate location in the sorted left block. The Insertion sort pseudo-code algorithm is: insertionsort(array){ for(i = 1; i < array.length; i++){ // array[i] is the element to be inserted temp = array[i]; insert temp in its proper location in the sorted subarray array[0]...array[i -1] Inserting temp in its proper location involves two steps: Finding the position k where temp is to be inserted. Shifting each of the elements array[k]...array[i -1] to the right by one slot //inserting to maintain ascending order temp = array[i]; k = i; while(k > 0 && array[k - 1] > temp){ array[k] = array[k - 1]; // shift value at index k-1 to location with index k k--; Unit 27 8 array[k] = temp; // insert array [i] at the right location with index k

Insertion Sort (cont d) The following java method implements Insertion sort algorithm and sorts the array according to the comparator object. public static void insertionsort(object[] array, Comparator comp){ int i,k; Object temp; for(i = 1; i < array.length ; i++){ temp = array[i]; k = i; while((k > 0)&& comp.compare(array[k-1],temp) > 0){ array[k] = array[k-1]; k--; array[k] = temp; Unit 27 9

Insertion Sort (cont d) To sort an array with k elements, Insertion sort requires k 1 passes. Example: Unit 27 10

Bubble Sort The basic idea is to compare two neighboring objects, and to swap them if they are in the wrong order During each pass, the largest object is pushed to the end of the unsorted sub-array. This will continue until the unsorted sub-array has one element. The Bubble (Exchange) sort pseudo-code algorithm is: bubblesort(array){ numberofpasses = 1; while(numberofpasses < array.length){ for(k = 1; k <= array.length numberofpasses; k++) swap array[k-1] and array[k] if they are out of order; numberofpasses++; Note: If no swaps occur in a complete for loop, the array is sorted. A boolean variable may be used to terminate the while loop prematurely. Unit 27 11

Bubble Sort (cont d) public static void bubblesort(object[] array, Comparator comp){ int pass = 1; Object temp; boolean sorted; do{ sorted = true; for(int m = 1; m <= array.length - pass; m++){ if(comp.compare(array[m - 1], array[m]) > 0){ temp = array[m-1]; // swap neighbors atm and m-1 array[m-1] = array[m]; array[m] = temp; sorted = false; // end of for loop pass++; while(! sorted); Unit 27 12

Bubble Sort (cont d) To sort an array with k elements, Bubble sort requires k 1 passes. Example: Unit 27 13

Exercises on Searching 1. What is a sequential search? 2. What is a binary search? 3. Write an iterative binarysearch method on an Object array. 4. Write a recursive binarysearch method on a double array. 5. Write a recursive linearsearch method on an Object array. 6. Write an iterative linearsearch method on a double array. 7. A binary search of an array requires that the elements be sorted in ascending order. 8. Suppose it is known that an array is sorted. When is linear search better than binary Search? 9. Mention the advantages, if any, of linear search over binary search. 10. Mention the advantages, if any, of binary search over linear search. 11. Mention the disadvantages, if any, of binary search over linear search. 12. Mention the disadvantages, if any, of linear search over binary search. 13. Design a Java program that will determine the average running times of binary search and linear search on sufficiently large integer arrays. 14. Each line of a text file contains the name of a person and his/her telephone number: firstname secondname telephonenumber The names may not be unique and may also not be sorted. The telephone numbers are also not sorted. Write a Java telephone lookup program that handles lookups by name as well as by telephone number. Use binary search for both lookups. Unit 27 14

Exercises on Searching (cont d) 15. An integer array of size 100 stores contiguous integers. What is the minimum number of comparisons to determine if: (a) a value is in the array? (b) a value is not in the array? 16. The information of students taking two courses is maintained in two Object arrays, course1 and course2. By defining an appropriate Student class, write a Java program to determine the students who are: (a) taking both courses. (b) not taking both courses. 17. The element being searched for is not in an array of 100 elements. What is the maximum number of comparisons needed in a sequential search to determine that the element is not there if the elements are: (a) completely unsorted? (b) sorted in ascending order? (c) sorted in descending order? 18. The element being searched for is not in an array of 100 elements. What is the average number of comparisons needed in a sequential search to determine that the element is not there if the elements are: (a) completely unsorted? (b) sorted in ascending order? (c) sorted in descending order? Unit 27 15

Exercises on Searching (cont d) 19. Implement each of the following Java String search methods: 20. Write a linear search method: public static Object linearsearch(object[] array, Object key) that returns null if the search is not successful; otherwise it returns a reference to the first matching object. 21. Write a binary search method: 21 public static Object binarysearch(object[] array, Object key) that returns null if the search is not successful; otherwise it returns a reference to the a matching object. Assume that the elements of the array are Comparable. Unit 27 16

Exercises on Searching (cont d) 22. Consider the following array of sorted integers: 10, 15, 25, 30, 33, 34, 46, 55, 78, 84, 96, 99 Using binary search algorithm, search for 23. Show the sequence of array elements that are compared, and for each comparison, indicate the values of low and high. Unit 27 17

Exercises on Sorting 1. Write a method: public static boolean issorted(object[] array, Comparator comparator) that returns true if array is sorted; otherwise it returns false. 2. Write a recursive bubble sort on a double array. 3. Write a recursive insertion sort on a double array. 4. Write a recursive selection sort on an Object array of Comparable objects. 5. Many operations can be performed faster on sorted than on unsorted data. For which of the following operations is this the case? (a) Finding an item with minimum value. (b) Computing an average of values. (c) Finding the middle value (the median). (d) Finding the value that appears most frequently in the data. (e) Finding the distinct elements of an array. (f) Finding a value closest to a given value. (g) Finding whether one word is an anagram (i.e., it contains the same letters) as another word. (example: plum and lump). 6. Rewrite some of the sorting methods we have studied such that each sorts an Object array of Comparable objects. 7. Show the contents of the following integer array: 43, 7, 10, 23, 18, 4, 19, 5, 66, 14 when the array is sorted in ascending order using: (a) bubble sort, (b) selection sort, (c) insertion sort. Unit 27 18

Exercises on Sorting (cont d) 8. Implement an insertion sort on an integer array that in each pass places both the minimum and maximum elements in their proper locations. 9. In our implementation of bubble sort, an array was scanned top-down to bubble down the largest element. What modifications are needed to make it work bottom-up to bubble up the smallest element? 10. A cocktail shaker sort is a modification of bubble sort in which the direction of bubbling changes in each iteration: In one iteration, the smallest element is bubbled up; in the next, the largest is bubbled down; in the next the second smallest is bubbled up; and so forth. Implement this algorithm. 11. Explain why insertion sort works well on partially sorted arrays. Unit 27 19