Docsity

Comparison of Sorting & Searching Algorithms: Binary, Selection, Insertion, Bubble, Quick,, Exams of Data Structures and Algorithms

Toggle sidebar
bg1
3/30/09!
1!
Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley
13.1 – Linear Search
!   A linear search simply examines each item in the
search pool, one at a time, until either the target is
found or until the pool is exhausted
!   This approach does not assume
the items in the search pool are in any particular order
!   We just need to be able to examine each element in
turn (in a linear fashion)
!   It's fairly easy to understand, but not very efficient
start!
Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley
13.1 – The linearSearch Algorithm
//-----------------------------------------------------------------
// Searches the specified array of objects using a linear search
// algorithm. Returns null if the target is not found.
//-----------------------------------------------------------------
public static Comparable linearSearch (Comparable[] data,
Comparable target)
{
Comparable result = null;
int index = 0;
while (result == null && index < data.length)
{
if (data[index].compareTo(target) == 0)
result = data[index];
index++;
}
return result;
}
Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley
13.1 – Binary Search
!   If the search pool is sorted,
then we can be more efficient than a linear search
!   A binary search eliminates large parts of the search pool with each
comparison
!   Instead of starting the search at one end, we begin in the middle
!   If the target isn't found, we know that if it is in the pool at all, it is in
one half or the other
!   We can then jump to the middle of that half, and continue similarly
start!
Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley
13.1 – The binarySearch Algorithm
//-----------------------------------------------------------------
// Searches the specified array of objects using a binary search
// algorithm. Returns null if the target is not found.
//-----------------------------------------------------------------
public static Comparable binarySearch (Comparable[] data,
Comparable target)
{
Comparable result = null;
int first = 0, last = data.length-1, mid;
while (result == null && first <= last)
{
mid = (first + last) / 2; // determine midpoint
if (data[mid].compareTo(target) == 0)
result = data[mid];
else
if (data[mid].compareTo(target) > 0)
last = mid - 1;
else
first = mid + 1;
}
return result;
}
pf3
pf4
pf5

Partial preview of the text

Download Comparison of Sorting & Searching Algorithms: Binary, Selection, Insertion, Bubble, Quick, and more Exams Data Structures and Algorithms in PDF only on Docsity!

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.1 – Linear Search

A linear search simply examines each item in the

search pool, one at a time, until either the target is

found or until the pool is exhausted

This approach does not assume

the items in the search pool are in any particular order

We just need to be able to examine each element in

turn (in a linear fashion)

It's fairly easy to understand, but not very efficient

start

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.1 – The linearSearch Algorithm

// Searches the specified array of objects using a linear search // //----------------------------------------------------------------- algorithm. Returns null if the target is not found. public static Comparable linearSearch (Comparable[] data, Comparable target) { Comparable result = null; int index = 0; while (result == null && index < data.length) { if (data[index].compareTo(target) == 0) result = data[index]; index++; } return result; } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.1 – Binary Search

If the search pool is sorted ,

then we can be more efficient than a linear search

A binary search eliminates large parts of the search pool with each

comparison

Instead of starting the search at one end, we begin in the middle

If the target isn't found, we know that if it is in the pool at all, it is in

one half or the other

We can then jump to the middle of that half, and continue similarly

start

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.1 – The binarySearch Algorithm

// Searches the specified array of objects using a binary search // //----------------------------------------------------------------- algorithm. Returns null if the target is not found. public static Comparable binarySearch (Comparable[] data, Comparable target) { Comparable result = null; int first = 0, last = data.length-1, mid; while (result == null && first <= last) { mid = (first + last) / 2; // determine midpoint if (data[mid].compareTo(target) == 0) result = data[mid]; else if (data[mid].compareTo(target) > 0) last = mid - 1; else first = mid + 1; } return result; }

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Sorting

Sorting is the process of arranging a group of items

into a defined order based on particular criteria

Many sorting algorithms have been designed

Sequential sorts typically require

about n^2 comparisons to sort n elements

Logarithmic sorts typically require

about nlog 2 n comparisons to sort n elements

As with searching, we must be able to compare one

element to another

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – SortPlayerList.java

//******************************************************************** // SortPlayerList.java Java Foundations // // Demonstrates a selection sort of Comparable objects. //******************************************************************** public { class SortPlayerList //----------------------------------------------------------------- // Creates an array of Contact objects, sorts them, then prints // //----------------------------------------------------------------- them. public { static void main (String[] args) Contact[] players = new Contact[7]; players[0] players[1] == newnew ContactContact ("Rodger", "Federer", "610-555-7384");("Andy", "Roddick", "215-555-3827"); players[2] players[3] == newnew ContactContact ("Maria", "Sharapova", "733-555-2969");("Venus", "Williams", "663-555-3984"); players[4] players[5] == newnew ContactContact ("Lleyton",("Eleni", "Daniilidou", "Hewitt", "464-555-3489"); "322-555-2284"); players[6] = new Contact ("Serena", "Williams", "243-555-2837"); Sorting.selectionSort(players); for (^) System.out.println(Comparable player : (player); players) }^ } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Contact.java

// Contact.java Java Foundations //******************************************************************** public class Contact implements Comparable { private String firstName, lastName, phone; public Contact (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; } public int compareTo (Object other) { int result; if (lastName.equals(((Contact)other).lastName)) result = firstName.compareTo(((Contact)other).firstName); else result = lastName.compareTo(((Contact)other).lastName); return result; } (…) (^) Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Selection Sort

Selection sort orders a list of values by

repetitively putting a particular value into its final position

More specifically

 find the smallest value in the list

 switch it with the value in the first position

 find the next smallest value in the list

 switch it with the value in the second position

 repeat until all values are in their proper places

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – The insertionSort Algorithm

// Sorts the specified array of objects using an insertion // //----------------------------------------------------------------- sort algorithm. public static void insertionSort (Comparable[] data) { for (int index = 1; index < data.length; index++) { Comparable key = data[index]; int position = index; // Shift larger values to the right while (position > 0 && data[position-1].compareTo(key) > 0) { data[position] = data[position-1]; position--; } data[position] = key; } } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Bubble Sort

Bubble sort orders a list of values by repetitively

comparing neighboring elements and swapping their

positions if necessary

More specifically

 scan the list, exchanging adjacent elements if they are not in

relative order; this bubbles the highest value to the top

 scan the list again, bubbling up the second highest value

 repeat until all elements have been placed in their proper order

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – The bubbleSort Algorithm

// Sorts the specified array of objects using a bubble sort // //----------------------------------------------------------------- algorithm. public static void bubbleSort (Comparable[] data) { int position, scan; for (position = data.length - 1; position >= 0; position--) { for (scan = 0; scan <= position - 1; scan++) if (data[scan].compareTo(data[scan+1]) > 0) swap (data, scan, scan+1); } } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Quick Sort

Quick sort orders a list of values by

partitioning the list around one element,

then sorting each partition:

 choose one element in the list to be the partition element

 organize the elements so that all elements less than the partition

element are to the left and all greater are to the right

 apply the quick sort algorithm (recursively) to both partitions

It would be nice if the partition element divided the list

roughly in half

QS has two methods

 quickSort – performs the recursive algorithm

 partition – rearranges the elements into two partitions

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – The quickSort Algorithm

// Sorts the specified array of objects using the quick sort // algorithm. //----------------------------------------------------------------- public static void quickSort (Comparable[] data, int min, int max) { int pivot; if (min < max) { pivot = partition (data, min, max); // make partitions quickSort(data, min, pivot-1); // sort left partition quickSort(data, pivot+1, max); // sort right partition } } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – The partition Algorithm

// (^) privateCreates static the partitions int partition needed (Comparable[] for quick sort. data, int min, int max) { // Use first element as the partition value Comparable partitionValue = data[min]; int left = min; int right = max; while { (left < right) // Search for an element that is > the partition element while left++; (data[left].compareTo(partitionValue) <= 0 && left < right) // Search while (data[right].compareTo(partitionValue) for an element that is < the partitionelement > 0) right--; if (left < right) swap(data, left, right); } // swap (data, min, Move the partition element right); to its final position return right; // That will become the pivot } Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – Merge Sort

Merge sort orders a list of values

by recursively dividing the list in half

until each sub-list has one element,

then recombining

More specifically

 divide the list into two roughly equal parts

 recursively divide each part in half, continuing until a part

contains only one element

 merge the two parts into one sorted list

 continue to merge parts as the recursion unfolds

Copyright © 2007 Pearson Education, Inc. Publishing s Pearson Addison-Wesley

13.2 – The decomposition of merge sort