1. Trang chủ
  2. » Công Nghệ Thông Tin

Lecture Java methods: Object-oriented programming and data structures (2nd AP edition): Chapter 14 - Maria Litvin, Gary Litvin

42 50 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 42
Dung lượng 278,28 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 14 - Searching and sorting. This chapter is a survey of the basic searching and sorting algorithms including the four standard sorting algorithms. This chapter’s objectives are to: Learn about the three ways to compare objects in Java, learn the following algorithms.

Trang 1

Searching and Sorting 14ACEHRPT

Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing All

rights reserved.

Java Methods

Object-Oriented Programming

and Data Structures

Maria Litvin ● Gary Litvin

2nd AP edition with GridWorld

Trang 2

Objectives:

• Learn about the three ways to compare objects in Java

• Learn the following algorithms

 Sequential and Binary Search

 Selection Sort and Insertion Sort

 Mergesort and Quicksort

• Learn about the java.util.Arrays and

java.util.Collections classes

Trang 3

Comparing Objects in Java

boolean result = obj1.equals(obj2);

int diff = obj1.compareTo(obj2);

int diff = c.compare(obj1, obj2);

Trang 6

• The equals method is properly defined in

String, Integer, Double, etc

Trang 7

obj1.compareTo(obj2)

• compareTo is an abstract method defined

in the java.util.Comparable<T> interface:

• Returns a positive integer if obj1 is

“greater than” obj2, a negative integer if

obj1 is “less than” obj2, zero if they are

“equal.”

public int compareTo (T other);

Sort of like obj1 - obj2

T is the type

parameter

Trang 8

it and make it agree with

compareTo

Trang 9

• compareTo is called polymorphically

from library methods, such as

Arrays.binarySearch(Object[ ] arr)

• Objects of classes that implement

Comparable are called “comparable”

(pronounced com-'parable).

• Strings, Integers, Doubles are

comparable

Trang 10

compareTo is

based on numerical values

Trang 11

compare(obj1, obj2)

• compare is an abstract method defined in

the java.util.Comparator<T> interface:

• Returns a positive integer if obj1 is

“greater than” obj2, a negative integer if

obj1 is “less than” obj2, zero if they are

“equal.”

public int compare (T obj1, T obj2);

Sort of like obj1 - obj2

T is the type

parameter

Trang 12

public class PetComparatorByName

Trang 13

• A programmer can define different

comparators to be used in different

situations

• compare is called from library methods, such as

Arrays.sort(T [ ] arr, Comparator<T> c)

(or from your own methods) that take a comparator object as a parameter

Trang 14

Ben 3

Cal 2

Dan

0

Eve 6

Fay 1

Guy 4

Trang 15

Sequential Search (cont’d)

public int sequentialSearch(Object [ ] arr, Object value) {

for (int i = 0; i < arr.length ; i++)

Trang 16

Sequential Search (cont’d)

• The average number of comparisons

(assuming the target value is equal to one of the elements of the array, randomly chosen)

is about n / 2 (where n = arr.length)

Worst case: n comparisons.

Also n comparisons are needed to establish

that the target value is not in the array

We say that this is an O(n) (order of n)

algorithm

Trang 17

Binary Search

• The elements of the list must be arranged

in ascending (or descending) order

• The target value is always compared with the middle element of the remaining

search range

• We must have random access to the

elements of the list (an array or ArrayList

are OK)

Trang 18

Binary Search (cont’d)

Fay 5

Dan 3

Cal 2

Amy

0

Guy 6

Ben 1

Eve 4

Eve?

Fay 5

Dan 3

Cal 2

Amy

0

Guy 6

Ben 1

Eve 4

Fay 5

Dan 3

Cal 2

Amy

0

Guy 6

Ben 1

Eve 4 Eve?

Eve!

Trang 19

return 1; // Not found

int middle = (left + right) / 2;

if (value == arr [middle] )

return middle;

else if (value < arr[middle])

return binarySearch (arr, value, left, middle 1);

else // if ( value > arr[middle])

return binarySearch (arr, value, middle + 1, right);

}

Trang 20

int middle = (left + right) / 2;

if ( value == arr [middle] )

Trang 21

Binary Search (cont’d)

• A “divide and conquer” algorithm

• Works very fast: only 20 comparisons are needed for an array of 1,000,000 elements; (30 comparisons can handle 1,000,000,000 elements; etc.)

We say that this is an O(log n) algorithm.

Trang 22

Sorting

• To sort means to rearrange the elements of a list in ascending or descending order

• Examples of sorting applications:

 a directory of files sorted by name or date

 bank checks sorted by account #

 addresses in a mailing list sorted by zip code

 hits found by a search engine sorted by relevance

 credit card transactions sorted by date

Trang 23

Sorting (cont’d)

• The algorithms discussed here are based on

“honest” comparison of values stored in an array No tricks

How fast can we sort an array of n elements?

 If we compare each element to each other we

need n(n-1) / 2 comparisons (that is, n2 by the

“order of magnitude.”)

 Faster “divide and conquer” sorting algorithms

need approximately n·log2 n comparisons (much

better).

Trang 25

Selection Sort

1 Select the max among the first n elements:

2 Swap it with the n-th element :

3 Decrement n by 1 and repeat from Step 1

Trang 26

double temp = arr [maxPos];

arr [maxPos] = arr [n 1];

Trang 27

Selection Sort (cont’d)

• The total number of comparisons is

always

(n-1) + (n-2) + + 1 = n(n-1) / 2

• No average, best, or worst case —

always the same

An O(n2) algorithm

Trang 28

Insertion Sort

1 k = 1; keep the first k elements in order.

2 Take the (k+1)-th element and insert among the first k in the right place.

3 Increment k by 1; repeat from Step 2 (while k < n)

k

k

Trang 30

Insertion Sort (cont’d)

• The average number of comparisons is

roughly half of the number in Selection Sort

• The best case is when the array is already

sorted: takes only (n-1) comparisons.

The worst case is n(n-1) / 2 when the array is

sorted in reverse order

On average, an O(n2) algorithm

Trang 31

Mergesort

1 Split the array into two roughly equal “halves.”

2 Sort (recursively) each half using Mergesort.

3 Merge the two sorted halves together.

7 6

2

Trang 32

Mergesort (cont’d)

public void mergesort (double[ ] arr,

int from, int to)

{

if (from <= to)

return;

int middle = (from + to ) / 2;

mergesort (arr, from, middle);

mergesort (arr, middle + 1, to);

if (arr [middle] > arr [middle + 1])

{

copy (arr, from, to, temp) ;

merge (temp, from, middle, to, arr);

Trang 33

Mergesort (cont’d)

Takes roughly n·log2 n comparisons.

• Without the shortcut, there is no best or worst case

• With the optional shortcut, the best case is

when the array is already sorted: takes only

(n-1) comparisons.

An O(n log n) algorithm.

Trang 34

Quicksort

1 Pick one element, called “pivot”

2 Partition the array, so that all the elements to the

left of pivot are pivot; all the elements to the right of pivot are pivot.

3 Sort recursively the left and the right segments using Quicksort.

Trang 35

Quicksort (cont’d)

Takes roughly n·log2 n comparisons.

• May get slow if pivot consistently fails to split the array into approximately equal halves

An O(n log n) algorithm.

Trang 36

The Benchmarks program

Enter the array size

Running time in milliseconds

Choose the sorting algorithm

Trang 37

java.util.Random

• Benchmarks uses the java.util.Random class

— a more controlled way to generate random numbers

• Constructors:

• If we set the same seed, we get the same

“random” sequence

Random generator1 = new Random();

Random generator2 = new Random(seed); long seed;

the seed is different each time

Trang 40

java.util.Collections

• Provides static methods for dealing with

ArrayLists and other Java collections

• Works for arrays of numbers, Strings, and

Trang 41

Binary Search?

Ngày đăng: 04/11/2020, 23:16

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN