Searching and Sorting Arrays. Searching in ordered and unordered arrays.

Slides:



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

MATH 224 – Discrete Mathematics
Updated QuickSort Problem From a given set of n integers, find the missing integer from 0 to n using O(n) queries of type: “what is bit[j]
CSE 373: Data Structures and Algorithms
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Simple Sorting Algorithms
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
Quicksort.
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Introduction to Computer Science Recursive Array Programming Recursive Sorting Algorithms Unit 16.
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.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
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.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
CS 2430 Day 28. Announcements We will have class in ULR 111 on Monday Exam 2 next Friday (sample exam will be distributed next week)
Problem Solving and Algorithms
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
SEARCHING (Linear/Binary). Searching Algorithms  method of locating a specific item of information in a larger collection of data.  two popular search.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
Searching. RHS – SOC 2 Searching A magic trick: –Let a person secretly choose a random number between 1 and 1000 –Announce that you can guess the number.
February 4, 2005 Searching and Sorting Arrays. Searching.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
Order Statistics. Order statistics Given an input of n values and an integer i, we wish to find the i’th largest value. There are i-1 elements smaller.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Searching and Sorting Arrays. Searching in ordered and unordered arrays.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
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 an array bubble and selection sorts. Sorting An arrangement or permutation of data An arrangement or permutation of data May be either: May be.
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.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
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.
CSCI 51 Introduction to Programming March 10, 2009.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
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
Simple Sorting Algorithms
Sorting array The bubblesort.
Quicksort 1.
Algorithm design and Analysis
Selection sort Given an array of length n,
Searching and Sorting Arrays
Search,Sort,Recursion.
Simple Sorting Algorithms
CSE 373 Data Structures and Algorithms
CSE 373 Sorting 1: Bogo Sort, Stooge Sort, Bubble Sort
Quicksort.
Simple Sorting Algorithms
Simple Sorting Algorithms
Module 8 – Searching & Sorting Algorithms
Sorting Algorithms.
Presentation transcript:

Searching and Sorting Arrays

Searching in ordered and unordered arrays

Find the minimal element in an unordered array.  Steps: 1. Initially, let the 0 th element be the minimal element. 2. Then sweep through the array and see if we find something better.

Find the minimal element in an unordered array. //Initially, let the 0 th element be // the minimal element. int whereSmallest = 0; //Then sweep through the array // and see if we find something better. How?

Find the minimal element in an unordered array. //Initially, let the 0 th element be // the minimal element. int whereSmallest = 0; //Then sweep through the array // and see if we find something better. for (int i=1; i<A.length; i++) { //check for something better How? }

Find the minimal element in an unordered array. //Initially, let the 0 th element be // the minimal element. int whereSmallest = 0; //Then sweep through the array // and see if we find something better. for (int i=1; i<A.length; i++) { //check for something better if (A[i]<A[whereSmallest]) { whereSmallest = i; } //at the end of the above loop, A[whereSmallest] is // the smallest element of A

Find the maximal element in an unordered array. What needs to be changed? //Initially, let the 0 th element be // the minimal element. int whereSmallest = 0; //Then sweep through the array // and see if we find something better. for (int i=1; i<A.length; i++) { //check for something better if (A[i]<A[whereSmallest]) { whereSmallest = i; } //at the end of the above loop, A[whereSmallest] is // the smallest element of A

Find the maximal element in an unordered array. What needs to be changed? //Initially, let the 0 th element be // the minimal element. int whereLargest = 0; //Then sweep through the array // and see if we find something better. for (int i=1; i<A.length; i++) { //check for something better if (A[i] > A[whereLargest]) { whereLargest = i; } //at the end of the above loop, A[whereLargest] is // the largest element of A

What if the array is already sort?  If the array is sorted in ascending order, where is the minimal element? We could search it as before but there is a better way.  If the array is sorted in ascending order, where is the maximal element?

What if the array is already sort?  If the array is sorted in descending order, where is the minimal element? We could search it as before but there is a better way.  If the array is sorted in descending order, where is the maximal element?

Statistical median  From wikipedia: “In probability theory and statistics, a median is a number dividing the higher half of a sample, a population, or a probability distribution from the lower half. The median of a finite list of numbers can be found by arranging all the observations from lowest value to highest value and picking the middle one. If there are an even number of observations, one often takes the mean of the two middle values.”  Given a sorted array, we can write a function that determines the median.

Statistical median public static double median ( int[] A ) { //determine if the array length is // odd of even double result = 0; … return result; }

Statistical median public static double median ( int[] A ) { //determine if the array length is // odd of even double result = 0; if ((A.length%2)==0) { //is this the odd or even case? … } else { … } return result; }

Statistical median public static double median ( int[] A ) { //determine if the array length is // odd of even double result = 0; if ((A.length%2)==0) { //even case so calc mean of middle 2 … } else { //odd case so pick middle one …This case is easier. } return result; }

Statistical median public static double median ( int[] A ) { //determine if the array length is // odd of even double result = 0; if ((A.length%2)==0) { //even case so calc mean of middle 2 … } else { //odd case so pick middle one result = A[ A.length/2 ]; } return result; }

Statistical median public static double median ( int[] A ) { //determine if the array length is // odd of even double result = 0; if ((A.length%2)==0) { //even case so calc mean of middle 2 result = ( A[ A.length/2-1 ] + A[ A.length/2 ] ) / 2.0; } else { //odd case so pick middle one result = A[ A.length/2 ]; } return result; }

Recap  So far we’ve: 1. Found min/max elements in unsorted and sorted arrays. 2. Calculated median of sorted arrays. 3. What if we would like to check whether or not an array contains a specified value? What type of thing should this function return?

Searching an unordered (unsorted) array for a specific element.

Unsorted search for specified element public static boolean unsortedSearch ( int[] A, int what ) { … }

Unsorted search for specified element public static boolean unsortedSearch ( int[] A, int what ) { boolean found = false; //now search A for what … return found; }

Unsorted search for specified element public static boolean unsortedSearch ( int[] A, int what ) { boolean found = false; //now search A for what for (int i=0; i<A.length; i++) { … } return found; }

Unsorted search for specified element public static boolean unsortedSearch ( int[] A, int what ) { boolean found = false; //now search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { found = true; } return found; }

Unsorted search for specified element: another slightly more efficient way public static boolean unsortedSearch ( int[] A, int what ) { //search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { return true; } return false; }

An analysis of these two methods  Let’s count the number of comparisons performed in: the best case the worst case the average case

An analysis of these two methods Method A public static boolean unsortedSearch ( int[] A, int what ) { boolean found = false; //now search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { found = true; } return found; } Method B public static boolean unsortedSearch ( int[] A, int what ) { //search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { return true; } return false; } What are the number of comparisons for the best, worse, and average cases for each method?

An analysis of these two methods Method A public static boolean unsortedSearch ( int[] A, int what ) { boolean found = false; //now search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { found = true; } return found; } Best = N; worst = N; average = N. Method B public static boolean unsortedSearch ( int[] A, int what ) { //search A for what for (int i=0; i<A.length; i++) { if (A[i]==what) { return true; } return false; } Best = 1; worst = N; average = N/2.

Searching a sorted array for a specified element.  We could treat the array as unsorted and search it but that would be inefficient.  So let’s introduce the binary search method.

Binary search first middlelast

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; … return foundIt; }

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case … return foundIt; }

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case if (first>=last) { if (what==A[first]) foundIt = true; } else { … } return foundIt; }

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case if (first>=last) { if (what==A[first]) foundIt = true; } else { int middle = (first+last) / 2; … } return foundIt; }

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case if (first>=last) { if (what==A[first]) foundIt = true; } else { int middle = (first+last) / 2; if (what==A[middle]) … else if (what<A[middle]) … else … } return foundIt; }

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case if (first>=last) { if (what==A[first]) foundIt = true; } else { int middle = (first+last) / 2; if (what==A[middle]) foundIt = true; else if (what<A[middle]) foundIt = sortedSearch( A, what, first, middle-1 ); else foundIt = sortedSearch( A, what, middle+1, last ); } return foundIt; } An example of a recursive function (a function that may call itself).

Searching a sorted array for a specified element. private static boolean sortedSearch ( int[] A, int what, int first, int last ) { boolean foundIt = false; //base case if (first>=last) { if (what==A[first]) foundIt = true; } else { int middle = (first+last) / 2; if (what==A[middle]) foundIt = true; else if (what<A[middle]) foundIt = sortedSearch( A, what, first, middle-1 ); else foundIt = sortedSearch( A, what, middle+1, last ); } return foundIt; } public static boolean sortedSearch ( int[] A, int what ) { return sortedSearch( A, what, 0, A.length-1 ); } An example of a “helper” function (a function that helps get the recursion started; not an “official” term). Also an example of function overloading (an “official” term).

Searching a sorted array for a specified element. private static boolean sortedSearch ( int[] A, int what, int first, int last ) { //base case if (first>=last) { if (what==A[first]) return true; } else { int middle = (first+last) / 2; if (what==A[middle]) return true; else if (what<A[middle]) return sortedSearch( A, what, first, middle-1 ); else return sortedSearch( A, what, middle+1, last ); } return false; } public static boolean sortedSearch ( int[] A, int what ) { return sortedSearch( A, what, 0, A.length-1 ); } Arguably simpler with returns.

Searching a sorted array for a specified element. public static boolean sortedSearch ( int[] A, int what ) { if (A.length==0)return false;//empty! int first = 0, last = A.length - 1; while (first<last) { int middle = (first+last) / 2; if (what == A[middle])return true; if (what < A[middle])last = middle - 1; elsefirst = middle + 1; } if (what==A[first])return true; return false; } Non recursive version.

Summary  Searching in an unordered array (of length N) requires us to search N elements in the worst case.  Searching in an ordered array (also of length N) requires us to search log 2 elements in the worst case.

Summary  Searching in an unordered array (of length N) requires us to search N elements in the worst case. So searching 1,000,000,000 things requires searching 1,000,000,000 things.  Searching in an ordered array (also of length N) requires us to search log 2 elements in the worst case. So searching 1,000,000,000 things requires searching only 30 things! At most!

Sorting an array: the selection sort

Sorting  An arrangement or permutation of data  May be either: ascending (non decreasing) descending (non increasing)

Selection sort  Based on the idea of repeatedly finding the minimal elements.  But first, how can we find the (single, most) minimal element in an array?

Selection sort How can we find the (single, most) minimal element in an array? … //let 0 be the location of the smallest element so far int whereSmallest = 0; for (int i=1; i<A.length; i++) { if (A[i]<A[whereSmallest]) { whereSmallest = i; } System.out.println( "the smallest is " + A[whereSmallest] + " which was located at position " + whereSmallest + "." ); …

Selection sort Idea: Find the smallest in A[0]..A[ A.length-1 ]. Put that in A[0]. Then find the smallest in A[1]..A[ A.length-1 ]. Put that in A[1]. … But first, let’s develop a swapPairs function that swaps a pair of elements denoted by a and b in some array, A.  

Selection sort public static void swapPair ( … ) { … } What do we need in here to do the job (function parameters)?

Selection sort public static void swapPair ( int[] A, int a, int b ) { … } What do we need in here to do the job (function parameters)?

Selection sort public static void swapPair ( int[] A, int a, int b ) { int temp = A[a]; A[a] = A[b]; A[b] = temp; }

Selection sort public static void swapPair ( int[] A, int a, int b ) { int temp = A[a]; A[a] = A[b]; A[b] = temp; } Why doesn’t this work? public static void swapPair ( int a, int b ) { int temp = a; a = b; b = temp; }

Selection sort Idea: Find the smallest in A[0]..A[ A.length-1 ]. Put that in A[0]. Then find the smallest in A[1]..A[ A.length-1 ]. Put that in A[1]. … //let 0 be the location of the smallest element so far int whereSmallest = 0; for (int i=1; i<A.length; i++) { if (A[i]<A[whereSmallest]) { whereSmallest = i; } swapPairs( A, 0, whereSmallest );

Selection sort Idea: Find the smallest in A[0]..A[ A.length-1 ]. Put that in A[0]. Then find the smallest in A[1]..A[ A.length-1 ]. Put that in A[1]. … for (int j=0; j<A.length; j++) { //let j be the location of the smallest element so far int whereSmallest = j; for (int i=j+1; i<A.length; i++) { if (A[i]<A[whereSmallest]) { whereSmallest = i; } swap( A, j, whereSmallest ); }