Searching and Sorting Copyright Prentice Hall (with modifications by Evan Korth)

22
Searching and Sorting Copyright Prentice Hall (with modifications by Evan Korth)
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    212
  • download

    0

Transcript of Searching and Sorting Copyright Prentice Hall (with modifications by Evan Korth)

Searching and Sorting

Copyright Prentice Hall

(with modifications by Evan Korth)

Searching ArraysSearching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching, like sorting, is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search.

Linear SearchThe linear search approach compares the key element, key, with each element in the array list[]. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.

Example 5.10Testing Linear Search

Objective: Implement and test the linear search method by creating an array of 10 elements of int type randomly and then display this array. Prompt the user to enter a key for testing the linear search.

LinearSearchLinearSearch RunRun

Searching Linear Search is not very efficient. In the worst case, the target we are searching could

be placed at the very end of the array, requiring that we search every single element in the array.

On average, the target might be somewhere in the middle of the array, requiring that we search half of all the elements in the array.

For example, if we had a 1000 element array:

– worst case: we must search 1000 elements

– on average: we search about 500 elements

Binary Search Binary Search is a more efficient option for searching

arrays. There are two tricks to using Binary Search:

– First, the array must be sorted. (Before you use Binary Search, you might first sort the array.)

– Second, Binary Search works be dividing the search area in half after each comparison (more on this soon.)

Binary Search is used very commonly in computer science, and there is a related concept called Binary Search Trees.

– If you take an Algorithms course, you will definitely spend time researching Binary Search Trees.

Binary Search Pseudo Code

1. Create a sorted array of sample data.

2. Prompt user for a search target.

3. Locate the middle of the array.

4. Compare the middle element with the search target:

a) If the search key is equal to the middle element, we have a match! Exit Loop

b) If the search key is less than the middle element, search the first half of the array (back to Step 4)

c) If the search key is larger than the middle element, search the second half of the array (back to Step 4)

Binary Search Applet

Search / Sort Applets: – http://www.cosc.canterbury.ac.nz/people/

mukundan/dsal/appldsal.html Blue: indicates that these elements have been

eliminated from the search.

Binary Search, cont.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

2 4 7 10 11 45 50 59 60 66 69 70 79

key = 11

key < 50

list

mid

[0] [1] [2] [3] [4] [5]

2 4 7 10 11 45

key > 7 mid

[3] [4] [5]

10 11 45

key = 11 mid

Example 5.11Testing Binary Search

Objective: Implement and test the binary search method. The program first creates an array of 10 elements of int type. It displays this array and then prompts the user to enter a key for testing binary search.

BinarySearchBinarySearch RunRun

Binary Search Efficiency

Binary Search is very efficient. For example, if you have 1024 elements in you array, in

the worst case, binary search only requires 10 comparisons.

– Linear Search Worst Case: 1024

– Binary Search Worst Case: 10 If you have 1 billion elements, binary search only requires

30 comparisons!

– Linear Search Worst Case: 1 billion

– Binary Search Worst Case: 30!

Sorting Sorting data is one of the most important

computing applications. Examples:

– Banks sort all checks by account number in order to prepare individual bank statements.

– Telephone companies sort accounts by last name, first name in order to create phone books.

Sorting data has attracted intense research efforts in computer science.

In this lecture, we explore the two of the simplest known sorting algorithms.

Selection Sort Applet Before examining any code, let us first try out a

Java applet for Bubble Sort. The Applet lets you step through each step in the

algorithm, so that you can gain an intuitive sense of how it works.

Just go to: http://math.hws.edu/TMCM/java/xSortLab/– Click the “Start Again” Button to get a new set of

random numbers.

– Click “Go” to sort.

– Click “Step” to step through the algorithm.

Example 5.12: (Cont) Using Arrays in Sorting

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // UnsortedFind the largest element in myList and swap it with the last element in myList.2, 9, 5, 4, 8, 1, 6 => 2, 6, 5, 4, 8, 1, 9 (size = 7)2, 6, 5, 4, 8, 1 => 2, 6, 5, 4, 1, 8 (size = 6)2, 6, 5, 4, 1 => 2, 1, 5, 4, 6 (size = 5)2, 1, 5, 4 => 2, 1, 4, 5 2, 1, 4 => 2, 1, 4,2, 1 => 1, 2Sort it to produce 1, 2, 4, 5, 6, 8, 9

Example 5.12Using Arrays in Sorting

Objective: Use the selectionSort method to write a program that will sort a list of double floating-point numbers.

int[] myList = {2, 9, 5, 4, 8, 1, 6}; // UnsortedSort it to produce 1, 2, 4, 5, 6, 8, 9 2, 9, 5, 4, 8, 1, 6

SelectionSortSelectionSort RunRun

Bubble Sort Bubble sort is another option for sorting a list of

numbers. It’s called bubble sort because

– larger values gradually “bubble” their way upward to the end of the array like air bubbles rising in water.

The technique is to make several passes through the array. – On each pass, pairs of elements are compared.

– If the pair is in increasing order, we leave the values as they are.

– If the pair is in decreasing order, we swap the values.

Bubble Sort Applet Before examining any code, let us first try out a

Java applet for Bubble Sort. The Applet lets you step through each step in the

algorithm, so that you can gain an intuitive sense of how it works.

Just go to: http://math.hws.edu/TMCM/java/xSortLab/– Click the “Start Again” Button to get a new set of

random numbers.

– Click “Go” to sort.

– Click “Step” to step through the algorithm.

Advantages / Disadvantages of Bubble Sort and Selection Sort

The main advantage of these two sorting algorithms is that it is easy to program.

The main disadvantage is that it is very slow. Much work in computer science has been geared

towards creating more efficient sorting algorithms. For example:

– Merge Sort– Bi-directional Bubble Sort– Quick Sort

For another quick demo, check out: http://java.sun.com/applets/jdk/1.1/demo/SortDemo/example1.html

Arrays of Objects

From chapter 6

Array of Objects Circle[] circleArray = new Circle[10];

An array of objects is actually an array of reference variables. So invoking circleArray[1].findArea() involves two levels of referencing as shown in the next figure. circleArray references to the entire array. circleArray[1] references to a Circle object.

Array of Objects, cont.

reference

Circle object 0 circleArray[0]

circleArray circleArray[1]

circleArray[9]

Circle object 9

Circle object 1

Circle[] circleArray = new Circle[10];

Array of Objects, cont.

Example 6.7: Summarizing the areas of the circles

TotalAreaTotalArea RunRun