Beruflich Dokumente
Kultur Dokumente
Chapter 4
Introduction to Algorithms
Selection Sort
Proceed through an array position by
position, starting with index 0. At the
current position, select the element from
the remaining elements that is next in
order and copy it into the current position.
Selection Sort Example Step 1
O rdered U n o rdered
O rdered U n o rdered
With the fish and owl in position, only the
last two animals must be ordered. We
identify the dog as the next-smallest
animal and have it exchange positions
with the dragon. After this step, the tail of
the list has only one item left, which must
be the largest animal. The entire list is
ordered.
Selection Sort in Action
selectionSort()
public static void selectionSort(int[] arr)
{
// index of smallest element in the sublist
int smallIndex;
int pass, j, n = arr.length;
int temp;
Output:
Sorted: 11 20 33 53 55 57 66 67 69 70
Sublists in an Array
A sublist of an array is a sequence of
elements whose range of indices begin at
index first and continue up to, but not
including last. Indicate a sublist using
the notation [first, last).
Sequential Search
Begin with a target value and an index
range [first, last). Scan the sublist
item by item, looking for the first
occurrence of a match with an item
named target. Return the index of the
match or -1 if target is not in the sublist.
The seqSearch() Method
seqSearch() Implementation
public static int seqSearch(int[] arr,
int first, int last, int target)
{
// scan indices in the range first
// <= i < last; return the index
// indicating the position if a match occurs;
// otherwise return -1
for (int i = first; i < last; i++)
if (arr[i] == target)
return i;
target = 23
Binary Search Success
Example Step 2
target = 23
Binary Search Success
Example Step 3
target = 23
Binary Search Failure
Example Step 1
target = 4
Binary Search Failure
Example Step 2
target = 4
Binary Search Failure
Example Step 3
target = 4
Binary Search Failure
Example Step 4
Index range [2,2). first ≥ last, so the search terminates
unsuccessfully. The return value is -1.
binSearch() Method
public static int binSearch(int arr[], int first,
int last, int target)
{
// index of the midpoint
int mid;
// value that is assigned arr[mid]
int midValue;
T(n) = n-1
Running Time: Selection Sort
Count the number of comparisons in the n-1
passes of the algorithm.
Constructor
Timing()
Create an instance of the class with all timing
variables set to 0.
Methods
void start()
Start the timing
double stop()
Stop the timing and return elapsed time in
seconds.
Timing Class Example
Timing sortTimer = new Timing();
double timeInSec;
System.out.println(
"Ratio of sequential to" +
"binary search time is " +
fmt.format(seqTime/binTime));
}
}
/*
Run: