Chapter 12 Binary Search and QuickSort Fundamentals of Java

Preview:

Citation preview

Chapter 12Binary Search and QuickSort

Fundamentals of Java

Fundamentals of Java 2

Vocabulary

Binary search algorithm QuickSort algorithm

Fundamentals of Java 3

Binary Search

Figure 12-9: List for the binary search algorithm with all numbers visible

Figure 12-8: Binary search algorithm (searching for 320)

Fundamentals of Java 4

Binary Search (cont.)

Table 12-4: Maximum number of steps needed to binary search lists of various sizes

Fundamentals of Java 5

Binary Search (cont.)

binary searches are O(log n).

Fundamentals of Java 6

Binary Search (cont.)

Figure 12-10: Steps in an iterative binary search for the number 320

Fundamentals of Java 7

Binary Search (cont.)

Fundamentals of Java 8

Quicksort

Sorting algorithms, such as insertion sort and bubble sort, are O(n2).

Quick Sort is O(n log n).– Break array into two parts and then move larger

values to one end and smaller values to other end.

– Recursively repeat procedure on each array half.

Fundamentals of Java 9

Quicksort (cont.)

Figure 12-11: An unsorted array

Phase 1:

Fundamentals of Java 10

Quicksort (cont.)

Phase 1 (cont.):

Fundamentals of Java 11

Quicksort (cont.)

Phase 1 (cont.):

Fundamentals of Java 12

Quicksort (cont.)

Phase 1 (cont.):

Fundamentals of Java 13

Quicksort (cont.)

Phase 1 (cont.):

Fundamentals of Java 14

Quicksort (cont.)

Phase 1 (cont.):

Phase 2 and beyond: Recursively perform phase 1 on each half of the array.

Fundamentals of Java 15

Quicksort (cont.)

Complexity analysis:– Amount of work in phase 1 is O(n).– Amount of work in phase 2 and beyond is O(n).

– In the typical case, there will be log2 n phases.

– Overall complexity will be O(n log2 n).

Fundamentals of Java 16

Quicksort (cont.)

Implementation:

Recommended