Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Starting out with Programming Logic and

Design
Fifth Edition

Chapter 9
Sorting and Searching
Arrays

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.1 The Bubble Sort Algorithm (1 of 3)
Bubble sort is a simple sorting algorithm for rearranging the
contents of an array
– Useful for alphabetical lists and numerical sorting
– Can be done in ascending or descending order
– With the Bubble Sort, array elements are compared and
numbers bubble toward the end of the array (assuming your
sorting in ascending order)
– Swapping elements must be done in order to properly sort
the array

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.1 The Bubble Sort Algorithm (2 of 3)

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.1 The Bubble Sort Algorithm (3 of 3)
Inside Program 9-1
– maxElement variable holds the subscript of the last
element that is to be compared to its neighbor
– index variable is an array subscript in one loop
– The outer loop iterates for each element in the array
– The inner loop iterates for each of the unsorted array
elements
– The if statement does the comparison
Sorting an array of strings to put information in alphabetical
order can be done with a Bubble Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.2 The Selection Sort Algorithm (1 of 3)
The selection sort works similar to the bubble sort, but more
efficient
– Bubble sort moves one element at a time
– Selection sort performs fewer swaps because it moves
items immediately to their final position

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.2 The Selection Sort Algorithm (2 of 3)
Figure 9-17 Flowchart for the selectionSort module

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.2 The Selection Sort Algorithm (3 of 3)
Inside Figure 9-17
– minIndex holds the subscript of the element with the
smallest value
– minValue holds the smallest value found
– The outer loop iterates for each element in the array, except
the last
– The inner loop performs the scan

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.3 The Insertion Sort Algorithm (1 of 3)
The insertion sort algorithm sorts the first two elements, which
becomes the sorted part of the array
– Each remaining element is then inserted into the sorted part
of the array at the correct location
– Also more efficient than the bubble sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.3 The Insertion Sort Algorithm (2 of 3)
Figure 9-24 Flowchart for the insertionSort module

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.3 The Insertion Sort Algorithm (3 of 3)
Inside Figure 9-24
– scan is used to scan through the array
– unsortedValue holds the first unsorted value
– The outer loop steps the index variable through each
subscript, starting at 1
– The inner loop moves the first element outside the sorted
subset and into its proper position

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
The Swap Module
A closer look at the swap module
– In most of the sorts, a swap module can be called
– It is the same in each sorting algorithm and only changes in
the parameter list to account for the type of data passed to
it

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.4 The Binary Search Algorithm (1 of 4)
The binary search algorithm locates an item in an array by
repeatedly dividing the array in half
– Each time it divides the array, it eliminates the half of the
array that does not contain the item
– It’s more sequential than the selection search because each
time it cuts the array in half and makes a smaller number of
comparisons to find a match

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.4 The Binary Search Algorithm (2 of 4)
How it works
– Requires that the array is first sorted
– The first comparison is done with the middle element of
the array to see if it is greater than or less than the number
that is being searched
– If it’s greater than, then the number must be in the first half
of the array
– If it’s less than, then the number must be in the second half
of the array
– This process is continued until the match if found

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.4 The Binary Search Algorithm (3 of 4)

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.4 The Binary Search Algorithm (4 of 4)
Inside Program 9-17
– middle is used to store the calculated middle index
– value stores the value being searched for
– A loop hold the search and iterates as long as there are
elements or until a match is found
– Nested if-then-else’s perform the comparisons

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.5 Focus on Languages: Java

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
public static void bubbleSort(int[] array)
{
int maxElement; // Marks the last element to compare
int index; // Index of an element to compare
int temp; // Used to swap to elements

// The outer loop positions maxElement at the last element


// to compare during each pass through the array. Initially
// maxElement is the index of the last element in the array.
// During each iteration, it is decreased by one.
for (maxElement = array.length - 1; maxElement >= 0; maxElement--)
{
// The inner loop steps through the array, comparing
// each element with its neighbor. All of the elements
// from index 0 thrugh maxElement are involved in the
// comparison. If two elements are out of order, they
// are swapped.
for (index = 0; index <= maxElement - 1; index++)
{
// Compare an element with its neighbor.
if (array[index] > array[index + 1])
{
// Swap the two elements.
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
}
} Java Bubble Sort
public static void selectionSort(int[] array)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
 
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (array.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];

// Scan the array, starting at the 2nd element in


// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
 
// Swap the element with the smallest value
// with the first element in the scannable area.
array[minIndex] = array[startScan];
array[startScan] = minValue; Java Selection Sort
}
}
public static void insertionSort(int[] array)
{
int unsortedValue; // The first unsorted value
int scan; // Used to scan the array

// The outer loop steps the index variable through


// each subscript in the array, starting at 1. This
// is because element 0 is considered already sorted.
for (int index = 1; index < array.length; index++)
{
// The first element outside the sorted subset is
// array[index]. Store the value of this element
// in unsortedValue.
unsortedValue = array[index];

// Start scan at the subscript of the first element


// outside the sorted subset.
scan = index;

// Move the first element outside the sorted subset


// into its proper position within the sorted subset.
while (scan > 0 && array[scan-1] > unsortedValue)
{
array[scan] = array[scan - 1];
scan--;
}

// Insert the unsorted value in its proper position


// within the sorted subset.
array[scan] = unsortedValue;
}
}
Java Insertion Sort
public static int binarySearch(String[] array, String value)
{
int first; // First array element
int last; // Last array element
int middle; // Mid point of search
int position; // Position of search value
boolean found; // Flag
 
// Set the inital values.
first = 0;
last = array.length - 1;
position = -1;
found = false;
 
// Search for the value.
while (!found && first <= last)
{
// Calculate mid point
middle = (first + last) / 2;

// If value is found at midpoint...


if (array[middle].equals(value))
{
found = true;
position = middle;
}
// else if value is in lower half...
else if (array[middle].compareTo(value) > 0)
last = middle - 1;
// else if value is in upper half....
else
first = middle + 1;
}
 
// Return the position of the item, or -1
// if it was not found.
return position;
}
Java Binary Search
9.5 Focus on Languages: Python

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
def bubble_sort(arr):
# Set max_element to the length of the arr list, minus
# one. This is necessary for the outer loop.
max_element = len(arr) - 1
 
# The outer loop positions max_element at the last element
# to compare during each pass through the list. Initially
# max_element is the index of the last element in the array.
# During each iteration, it is decreased by one.
while max_element >= 0:
# Set index to 0, necessary for the inner loop.
index = 0
 
# The inner loop steps through the list, comparing
# each element with its neighbor. All of the elements
# from index 0 thrugh max_element are involved in the
# comparison. If two elements are out of order, they
# are swapped.
while index <= max_element - 1:
# Compare an element with its neighbor.
if arr[index] > arr[index + 1]:
# Swap the two elements.
temp = arr[index]
arr[index] = arr[index + 1]
arr[index + 1] = temp
# Increment index.
index = index + 1
# Decrement max_element.
max_element = max_element - 1

Python Bubble Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
def selection_sort(arr):
# Set start_scan to 0. This is necessary for
# the outer loop. It is the starting position
# of the scan.
start_scan = 0
 
# The outer loop iterates once for each element in the
# list. The start_scan variable marks the position where
# the scan should begin.
while start_scan < len(arr) - 1:
# Assume the first element in the scannable area
# is the smallest value.
min_index = start_scan
min_value = arr[start_scan]
 
# Initialize index for the inner loop.
index = start_scan + 1
 
# Scan the list, starting at the 2nd element in
# the scannable area. We are looking for the smallest
# value in the scannable area.
while index < len(arr):
if arr[index] < min_value:
min_value = arr[index]
min_index = index
# Increment index.
index = index + 1
 
# Swap the element with the smallest value
# with the first element in the scannable area.
arr[min_index] = arr[start_scan]
arr[start_scan] = min_value
 
# Increment start_scan.
start_scan = start_scan + 1
Python Selection Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
def insertion_sort(arr):
# Set index to 1 for the outer loop.
index = 1

# The outer loop steps the index variable through


# each subscript in the list, starting at 1. This
# is because element 0 is considered already sorted.
while index < len(arr):
# The first element outside the sorted subset is
# arr[index]. Assign the value of this element
# to unsorted_value.
unsorted_value = arr[index]

# Start the scan variable at the subscript of the


# first element outside the sorted subset.
scan = index

# Move the first element outside the sorted subset


# into its proper position within the sorted subset.
while scan > 0 and arr[scan - 1] > unsorted_value:
arr[scan] = arr[scan - 1]
scan = scan - 1

# Insert the unsorted value in its proper position


# within the sorted subset.
arr[scan] = unsorted_value

# Increment index.
index = index + 1

Python Insertion Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
def binary_search(arr, value):
# Set the initial values.
first = 0
last = len(arr) - 1
position = -1
found = False

# Search for the value


while not found and first <= last:
# Calculate the mid point.
middle = (first + last) / 2

# If the value is found at the mid point...


if arr[middle] == value:
found = True
position = middle
# else if value is in the lower half...
elif arr[middle] > value:
last = middle - 1
# else if value is in the upper half...
else:
first = middle + 1

# Return the position of the item, or -1


# if it was not found.
return position

Python Binary Search


Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
9.5 Focus on Languages: C++

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
void bubbleSort(int array[], int size)
{
int maxElement; // Marks the last element to compare
int index; // Index of an element to compare

// The outer loop positions maxElement at the last element


// to compare during each pass through the array. Initially
// maxElement is the index of the last element in the array.
// During each iteration, it is decreased by one.
for (maxElement = size - 1; maxElement >= 0; maxElement--)
{
// The inner loop steps through the array, comparing
// each element with its neighbor. All of the elements
// from index 0 thrugh maxElement are involved in the
// comparison. If two elements are out of order, they
// are swapped.
for (index = 0; index <= maxElement - 1; index++)
{
// Compare an element with its neighbor.
if (array[index] > array[index + 1])
{
// Swap the two elements.
swap(array[index], array[index+1]);
}
}
}
}
 
// The swap function swaps the contents of the two
// arguments passed to it.
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
} C++ Bubble Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
void selectionSort(int array[], int size)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
 
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (size-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];

// Scan the array, starting at the 2nd element in


// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
 
// Swap the element with the smallest value
// with the first element in the scannable area.
swap(array[minIndex], array[startScan]);
}
}
 
// The swap function swaps the contents of the two
// arguments passed to it.
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;

}
b = temp;
C++ Selection Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
void insertionSort(int array[], int size)
{
int unsortedValue; // The first unsorted value
int scan; // Used to scan the array

// The outer loop steps the index variable through


// each subscript in the array, starting at 1. This
// is because element 0 is considered already sorted.
for (int index = 1; index < size; index++)
{
// The first element outside the sorted subset is
// array[index]. Store the value of this element
// in unsortedValue.
unsortedValue = array[index];

// Start scan at the subscript of the first element


// outside the sorted subset.
scan = index;

// Move the first element outside the sorted subset


// into its proper position within the sorted subset.
while (scan > 0 && array[scan-1] > unsortedValue)
{
array[scan] = array[scan - 1];
scan--;
}

// Insert the unsorted value in its proper position


// within the sorted subset.
array[scan] = unsortedValue;
}
}
C++ Insertion Sort

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
int binarySearch(string array[], string value, int size)
{
int first; // First array element
int last; // Last array element
int middle; // Midpoint of search
int position; // Position of search value
bool found; // Flag
 
// Set the inital values.
first = 0;
last = size - 1;
position = -1;
found = false;
 
// Search for the value.
while (!found && first <= last)
{
// Calculate midpoint
middle = (first + last) / 2;

// If value is found at midpoint...


if (array[middle] == value)
{
found = true;
position = middle;
}
// else if value is in lower half...
else if (array[middle] > value)
last = middle - 1;
// else if value is in upper half....
else
first = middle + 1;
}
 
// Return the position of the item, or -1
// if it was not found.
return position;
}
C++ Binary Search
Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved
Copyright

Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved

You might also like