sorting and searching arrays csc 1401: introduction to programming with java week 12 – lectures 1...

23
Sorting and Searching Sorting and Searching Arrays Arrays CSC 1401 CSC 1401 : Introduction to Programming : Introduction to Programming with Java with Java Week 12 – Lectures 1 & 2 Week 12 – Lectures 1 & 2 Wanda M. Kunkle Wanda M. Kunkle

Post on 22-Dec-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Sorting and Searching ArraysSorting and Searching Arrays

CSC 1401CSC 1401: Introduction to Programming with Java: Introduction to Programming with JavaWeek 12 – Lectures 1 & 2Week 12 – Lectures 1 & 2

Wanda M. KunkleWanda M. Kunkle

22

Sorting an ArraySorting an Array

The data stored in an array can be manipulated most The data stored in an array can be manipulated most efficiently if it is sorted.efficiently if it is sorted.

Data can be sorted using one of two orderings:Data can be sorted using one of two orderings: AscendingAscending DescendingDescending

There are many different algorithms for sorting There are many different algorithms for sorting arrays, some more efficient than others.arrays, some more efficient than others.

The first algorithm we will look at is bubble sort, one The first algorithm we will look at is bubble sort, one of the simplest, but also one of the least efficient of of the simplest, but also one of the least efficient of the lot.the lot.

33

Bubble SortBubble Sort

Sorting algorithm in which smaller values “bubble” Sorting algorithm in which smaller values “bubble” their way to the top of the array (i.e., toward the first their way to the top of the array (i.e., toward the first element), while larger values sink to the bottom of the element), while larger values sink to the bottom of the array (i.e., toward the last element)array (i.e., toward the last element)

Basically, bubble sort:Basically, bubble sort: Passes through the array from beginning to end …Passes through the array from beginning to end … Compares adjacent pairs of elements ...Compares adjacent pairs of elements ... Interchanges any two elements that are out of order …Interchanges any two elements that are out of order … Repeats this process until the array is sorted.Repeats this process until the array is sorted.

44

Bubble SortBubble Sort The number of passes required to sort an array using The number of passes required to sort an array using

bubble sort is generally n – 1, where n is the size of bubble sort is generally n – 1, where n is the size of the array.the array.

At the end of the first pass, the largest element will be At the end of the first pass, the largest element will be in the last index of the array (assuming an ascending in the last index of the array (assuming an ascending sort).sort).

At the end of the second pass, the second largest At the end of the second pass, the second largest element will be in the next-to-last index of the array element will be in the next-to-last index of the array (assuming an ascending sort).(assuming an ascending sort).

The process continues in like manner until the array The process continues in like manner until the array is completely sorted.is completely sorted.

55

Algorithm AnimationAlgorithm Animation

To understand how the bubble sort algorithm To understand how the bubble sort algorithm works, let’s look at an animation of it.works, let’s look at an animation of it.

The following Java applet The following Java applet animatesanimates bubble bubble sort, as well as other sorting algorithms:sort, as well as other sorting algorithms: Sort AnimationSort Animation

66

Sample ProgramSample Program

Now let’s look at the code for bubble sort.Now let’s look at the code for bubble sort. The following Java program The following Java program implementsimplements the the

bubble sort algorithm:bubble sort algorithm: Bubblesort.javaBubblesort.java

77

Lab 11Lab 11

Finally, let’s take another look at this past Finally, let’s take another look at this past Friday’s lab, since many of you still seem to Friday’s lab, since many of you still seem to have questions about it.have questions about it.

88

Selection SortSelection Sort

The second algorithm we will look at for The second algorithm we will look at for sorting arrays is selection sort.sorting arrays is selection sort.

Selection sort, like bubble sort, is simple, yet Selection sort, like bubble sort, is simple, yet inefficient. (Unfortunately, the two sorting inefficient. (Unfortunately, the two sorting algorithms are equally inefficient. algorithms are equally inefficient. ))

99

Selection SortSelection Sort

Sorting algorithm which proceeds by repeatedly Sorting algorithm which proceeds by repeatedly dividing an array into two subarrays, one that is dividing an array into two subarrays, one that is sorted and one that is not, until the entire array is sorted and one that is not, until the entire array is sortedsorted

Basically, selection sort works as follows:Basically, selection sort works as follows: Find the smallest value in the array …Find the smallest value in the array … Swap it with the value in the first position ...Swap it with the value in the first position ... Repeat the above steps for the remaining unsorted subarray Repeat the above steps for the remaining unsorted subarray

(starting at the second position) …(starting at the second position) … Continue this process until the entire array is sorted.Continue this process until the entire array is sorted.

1010

Selection SortSelection Sort The number of passes required to sort an array using The number of passes required to sort an array using

selection sort is generally n – 1, where n is the size of selection sort is generally n – 1, where n is the size of the array.the array.

At the end of the first pass, the smallest element will At the end of the first pass, the smallest element will be in the first (0be in the first (0thth) index of the array (assuming an ) index of the array (assuming an ascending sort).ascending sort).

At the end of the second pass, the second smallest At the end of the second pass, the second smallest element will be in the second (1element will be in the second (1thth) index of the array ) index of the array (assuming an ascending sort).(assuming an ascending sort).

The process continues in this fashion until the array is The process continues in this fashion until the array is completely sorted.completely sorted.

1111

Algorithm AnimationAlgorithm Animation

To understand how the selection sort algorithm To understand how the selection sort algorithm works, let’s look at an animation of it.works, let’s look at an animation of it.

The following Java applet The following Java applet animatesanimates selection selection sort, as well as other sorting algorithms:sort, as well as other sorting algorithms: Sort AnimationSort Animation

1212

Sample ProgramSample Program

Now let’s look at the code for selection sort.Now let’s look at the code for selection sort. The following Java program The following Java program implementsimplements the the

selection sort algorithm:selection sort algorithm: SelectionSort.javaSelectionSort.java

1313

Searching an ArraySearching an Array

Two algorithms commonly used to search an array are:Two algorithms commonly used to search an array are: Linear (or sequential) searchLinear (or sequential) search

Searches for a target value in an array by examining each element in Searches for a target value in an array by examining each element in sequence sequence

Does not require that the array be sortedDoes not require that the array be sorted Simple, inefficient searching algorithmSimple, inefficient searching algorithm

Binary searchBinary search Searches for a target value in an array using a halving algorithmSearches for a target value in an array using a halving algorithm Requires that the array be sortedRequires that the array be sorted Complex, efficient searching algorithmComplex, efficient searching algorithm

1414

Sample ProgramsSample Programs

The following Java programs demonstrate The following Java programs demonstrate linear search of an array:linear search of an array: gradeSearch.javagradeSearch.java (unsorted array) (unsorted array) gradeSearchWithSort.java (sorted array)gradeSearchWithSort.java (sorted array)

1515

Binary SearchBinary Search

Binary search, unlike linear search, requires Binary search, unlike linear search, requires that the array be sorted.that the array be sorted.

The algorithm proceeds as follows:The algorithm proceeds as follows: Compare the target value to the value in the middle Compare the target value to the value in the middle

(or approximate middle) of the array; if the two (or approximate middle) of the array; if the two values match, we’re done; otherwise …values match, we’re done; otherwise …

Search the bottom half of the array if the target Search the bottom half of the array if the target value is less than the middle value; otherwise …value is less than the middle value; otherwise …

Search the top half of the array if the target value Search the top half of the array if the target value is greater than the middle value.is greater than the middle value.

1616

Binary SearchBinary Search

Algorithm in pseudocode (1Algorithm in pseudocode (1stst version): * version): * midmid = approximate midpoint between= approximate midpoint between 00 andand (a.length – 1);(a.length – 1);

if (target == a[mid])if (target == a[mid]) return mid; return mid;else if (target < a[mid])else if (target < a[mid])

return the result of searching return the result of searching a[0]a[0] through through a[mid – 1]a[mid – 1]..else if (target > a[mid])else if (target > a[mid])

return the result of searchingreturn the result of searching a[mid + 1]a[mid + 1] throughthrough a[a.length – 1]a[a.length – 1]..

Smaller versions of the problem we’re trying to solve; correspond Smaller versions of the problem we’re trying to solve; correspond to recursive calls to the algorithm itselfto recursive calls to the algorithm itself

* Lecture material adapted from Java: An Introduction to Problem Solving & Programming by Walter Savitch

1717

Binary SearchBinary Search

Algorithm in pseudocode (2Algorithm in pseudocode (2ndnd version): * version): * midmid = approximate midpoint between= approximate midpoint between firstfirst andand last;last;

if (target == a[mid])if (target == a[mid]) return mid; return mid;else if (target < a[mid])else if (target < a[mid])

return the result of searching return the result of searching a[first]a[first] through through a[mid – 1]a[mid – 1]..else if (target > a[mid])else if (target > a[mid])

return the result of searchingreturn the result of searching a[mid + 1]a[mid + 1] throughthrough a[last]a[last]..

Using Using firstfirst and and lastlast to specify the indices of the range of to specify the indices of the range of values to be searched allows the algorithm to be called values to be searched allows the algorithm to be called recursivelyrecursively

* Lecture material adapted from Java: An Introduction to Problem Solving & Programming by Walter Savitch

1818

Binary SearchBinary Search Algorithm in pseudocode (3Algorithm in pseudocode (3rdrd version): * version): *

midmid = approximate midpoint between= approximate midpoint between firstfirst andand last;last;if (first > last)if (first > last) return -1; return -1;else if (target == a[mid])else if (target == a[mid]) return mid; return mid;else if (target < a[mid])else if (target < a[mid]) return the result of searching return the result of searching a[first]a[first] through through a[mid – 1]a[mid – 1]..else if (target > a[mid])else if (target > a[mid]) return the result of searchingreturn the result of searching a[mid + 1]a[mid + 1] throughthrough a[last]a[last]..

This version of the algorithm handles the case where This version of the algorithm handles the case where targettarget (the number (the number being searched for) is not found in the array.being searched for) is not found in the array.

When this occurs, the value of When this occurs, the value of firstfirst becomes larger than the value of becomes larger than the value of last last (condition one).(condition one).

* Lecture material adapted from Java: An Introduction to Problem Solving & Programming by Walter Savitch

1919

Sample ProgramsSample Programs

The following Java program demonstrates The following Java program demonstrates binary search of an array:binary search of an array: BinaryGradeSearch.java (sorted array)BinaryGradeSearch.java (sorted array)

2020

Merge SortMerge Sort

Merge sort is a divide-and-conquer algorithm Merge sort is a divide-and-conquer algorithm which works as follows:which works as follows: The array to be sorted is divided into two halves.The array to be sorted is divided into two halves. Each half is sorted by recursive calls.Each half is sorted by recursive calls. The two sorted arrays are then merged into a single The two sorted arrays are then merged into a single

sorted array.sorted array. An outline of the algorithm appears on the An outline of the algorithm appears on the

next slide.next slide.

2121

Merge Sort AlgorithmMerge Sort Algorithm

If an array If an array aa consists of a single element, do nothing consists of a single element, do nothing (base case).(base case).

Otherwise, do the following (recursive case):Otherwise, do the following (recursive case): Copy the elements in the first half of array Copy the elements in the first half of array aa to an array to an array

named named frontfront.. Copy the elements in the last half of array Copy the elements in the last half of array aa to an array to an array

named named tailtail.. Sort Sort frontfront with a recursive call. with a recursive call. Sort Sort tailtail with a recursive call. with a recursive call. Merge the elements in arrays Merge the elements in arrays frontfront and and tailtail into array into array aa..

2222

Algorithm AnimationAlgorithm Animation

To understand how the merge sort algorithm To understand how the merge sort algorithm works, let’s look at an animation of it.works, let’s look at an animation of it.

The following Java applet The following Java applet animatesanimates merge merge sort:sort: Merge SortMerge Sort

The following Java applets The following Java applets animateanimate merge merge sort, as well as other sorting algorithms:sort, as well as other sorting algorithms: Sorting AppletsSorting Applets

2323

Sample ProgramSample Program

Now let’s look at the code for merge sort.Now let’s look at the code for merge sort. The following Java program The following Java program implementsimplements the the

merge sort algorithm:merge sort algorithm: MergeSort.javaMergeSort.java