1 / 82

Chapter 9 Sorting and Searching Arrays

Chapter 9 Sorting and Searching Arrays. Sorting an Array Searching an Array Analysis of Algorithms. Sorting an Array. Rearrange the contents to be in ascending order Very common activity for computers Phone books Business reports Lists of files How to do it?. Sorting an Array.

Download Presentation

Chapter 9 Sorting and Searching Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 9Sorting and Searching Arrays Sorting an Array Searching an Array Analysis of Algorithms

  2. Sorting an Array • Rearrange the contents to be in ascending order • Very common activity for computers • Phone books • Business reports • Lists of files • How to do it? Programming and Problem Solving With Java

  3. Sorting an Array • Many sorting algorithms, but basically two groups • Algorithms that are simple and slow • Algorithms that are complex and fast • Simple and slow algorithms • Selection sort • Insertion sort • Bubble sort • Complex and fast algorithms • Merge sort • Heap sort • Quick sort • Will examine selection and merge sort Programming and Problem Solving With Java

  4. Sorting an Array: Selection Sort • Selection sort • Simple and slow algorithm • Let's see how it sorts this array Programming and Problem Solving With Java

  5. Sorting an Array: Selection Sort • Step 1 • Find the element that goes in location 0 • Swap that with the element in location 0 sorted portion of array Programming and Problem Solving With Java

  6. Sorting an Array: Selection Sort • Step 2 • Find the element that goes in location 1 • Swap that with the element in location 1 sorted portion of array Programming and Problem Solving With Java

  7. Sorting an Array: Selection Sort • Remaining steps similar • Find the element that goes in next location • Swap that with the element in that location array is sorted! Programming and Problem Solving With Java

  8. Sorting an Array: Selection Sort • Selection sort algorithm • Step 0: Search the whole array for the smallest element. Exchange that element with the element in location 0. • Step 1: Search the array from location 1 to the end for the smallest element. Exchange that element with the element in location 1. • Step 2: Search the array from location 2 to the end for the smallest element. Exchange that element with the element in location 2. • Steps 3, ...: Continue in this way for all the other locations in the array. Programming and Problem Solving With Java

  9. Sorting an Array: Selection Sort • Selection sort in Java • // selectionSort: Returns the contents of array sorted in ascending • // order • static void selectionSort(double[] array) • { • int locationOfSmallest; • double temp; • for (int step = 0; step < array.length; step++) • { • // Find the location of the smallest element from array[step] • // to the end of the array • locationOfSmallest = step; • for (int loc = step; loc < array.length; loc++) • { • if (array[loc] < array [locationOfSmallest]) • { • locationOfSmallest = loc; • } • } • // Exchange array[step] with array[locationOfSmallest] • temp = array[step]; • array[step] = array[locationOfSmallest]; • array[locationOfSmallest] = temp; • } • } Programming and Problem Solving With Java

  10. Sorting an Array: Merge Sort • Much faster sort algorithm than selection sort Programming and Problem Solving With Java

  11. Sorting an Array: Merge Sort • Uses process of merging two sorted sets 1. Compare the topmost index card from each list 2. Put the smaller of the two, on the back of the new list 3. Continue steps 1 and 2 until one of the lists is empty 4. Put the rest of the cards on the back of the new list Programming and Problem Solving With Java

  12. Sorting an Array: Merge Sort • Merge pseudocode • while (both lists still have elements) • { • if (list1 has the smallest element on top) • { • remove the topmost element from list1 and put on the output list • } • else • { • remove the topmost element from list2 and put on the output list • } • } • if (list1 still has remaining elements) • { • move remaining elements from list1 to the output list • } • if (list2 still has remaining elements) • { • move remaining elements from list2 to the output list • } Programming and Problem Solving With Java

  13. Sorting an Array: Merge Sort • Example of merging: the mergeArrays() method • // Merges two arrays and displays the merged array. • // Demonstrates use of the mergeArrays() method. • public class DemonstrateMergeArrays • { • // mergeArrays: Returns the merge of arrays firstSource and • // secondSource. Elements of firstSource and • // secondSource must be in ascending order • static double[] mergeArrays(double[] firstSource, • double[] secondSource) • { • ... • } • public static void main(String[] args) • { • double[] firstArray = {2.4, 4.6, 8.6, 9.4}; • double[] secondArray = {1.3, 5.1, 6.7, 7.9}; • double[] mergedArray = mergeArrays(firstArray, secondArray); • for (int i = 0; i < mergedArray.length; i++) • { • System.out.println(mergedArray[i]); • } • } • } codegoes here Programming and Problem Solving With Java

  14. Sorting an Array: Merge Sort • Method mergeArrays() • // mergeArrays: Returns the merge of arrays firstSource and • // secondSource. Elements of firstSource and • // secondSource must be in ascending order • static double[] mergeArrays(double[] firstSource, • double[] secondSource) • { • double[] target = new double[firstSource.length • + secondSource.length]; • int firstIndex = 0, secondIndex = 0, targetIndex = 0; • // Merge elements from firstSource and secondSource into • // target, until all elements from either firstSource or • // secondSource are copied • while (firstIndex < firstSource.length • && secondIndex < secondSource.length) • { • if (firstSource[firstIndex] < secondSource[secondIndex]) • { • target[targetIndex] = firstSource[firstIndex]; • firstIndex++; • } • else • { • target[targetIndex] = secondSource[secondIndex]; • secondIndex++; • } • targetIndex++; • } Programming and Problem Solving With Java

  15. Sorting an Array: Merge Sort • Method mergeArrays() (continued) • // If anything left in firstSource, append it to target • while (firstIndex < firstSource.length) • { • target[targetIndex] = firstSource[firstIndex]; • targetIndex++; • firstIndex++; • } • // If anything left in secondSource, append it to target • while (secondIndex < secondSource.length) • { • target[targetIndex] = secondSource[secondIndex]; • targetIndex++; • secondIndex++; • } • return target; • } Programming and Problem Solving With Java

  16. Sorting an Array: Merge Sort • How mergeArrays() works Programming and Problem Solving With Java

  17. Sorting an Array: Merge Sort • How Merge Sort works • Original array to sort • Merge sort also requires an empty array (work) Programming and Problem Solving With Java

  18. Sorting an Array: Merge Sort • How Merge Sort works • Merge individual elements into pairs -- in work array Programming and Problem Solving With Java

  19. Sorting an Array: Merge Sort • How Merge Sort works (continued) • Merge pairs from work array into groups of 4 in the original array Programming and Problem Solving With Java

  20. Sorting an Array: Merge Sort • How Merge Sort works (continued) • Merge groups of 4 from original array into groups of 8 (or less) in the work array Programming and Problem Solving With Java

  21. Sorting an Array: Merge Sort • How Merge Sort works (continued) • Result is sorted, but in work array • Must copy elements back to original array Programming and Problem Solving With Java

  22. Sorting an Array: Merge Sort • Merge sort steps • Each element in the array is a single partition. Merge adjacent partitions to a new array, resulting in partitions of size two. Assign the new array to the original. • Each pair of elements in the array is a single partition. Merge adjacent partitions to another new array, resulting in partitions of size four. Assign the new array to the original. • Each group of four elements in the original array is a single partition. Merge adjacent partitions to another new array, resulting in partitions of size eight. Assign the new array to the original. • Continue this process until the partition size isat least as large as the whole array. Programming and Problem Solving With Java

  23. Sorting an Array: Merge Sort • Merge sort in Java • Uses mergePass method -- like mergeArrays(), but input is partitions in a single array, output is a partition in an array • // mergePass: Returns contents of source array in which each • // consecutive sequence of elements of length • // partitionLen * 2 is sorted • static double[] mergePass(double[] source, int partitionLen) • { • int firstPart = 0, secondPart = 0, firstIndex, secondIndex, • targetIndex, firstEnd, secondEnd; • double[] target = new double[source.length]; • // Merge adjacent pairs of partitions • while (firstPart < source.length) • { • secondPart = firstPart + partitionLen; • firstIndex = firstPart; • secondIndex = secondPart; • targetIndex = firstPart; • firstEnd = Math.min(firstPart + partitionLen, source.length); • secondEnd = Math.min(secondPart + partitionLen, source.length); "work" array allocated for each call to mergePass() Programming and Problem Solving With Java

  24. Sorting an Array: Merge Sort • Merge sort in Java (continued) • // Merge elements from first partition and second partition into • // target, until all elements from either first partition or • // second partition are copied • while (firstIndex < firstEnd && secondIndex < secondEnd) • { • if (source[firstIndex] < source [secondIndex]) • { • target[targetIndex] = source[firstIndex]; • firstIndex++; • } • else • { • target[targetIndex] = source[secondIndex]; • secondIndex++; • } • targetIndex++; • } • // If anything left in first partition, append it to target. • while (firstIndex < firstEnd) • { • target[targetIndex] = source[firstIndex]; • targetIndex++; • firstIndex++; • } Programming and Problem Solving With Java

  25. Sorting an Array: Merge Sort • Merge sort in Java (continued) • // If anything left in second partition, append it to target • while (secondIndex < secondEnd) • { • target[targetIndex] = source[secondIndex]; • targetIndex++; • secondIndex++; • } • firstPart = secondPart + partitionLen; • } • return target; • } • // mergeSort: Returns the contents of array in ascending order • static double[] mergeSort(double[] array) • { • int partitionLen = 1, index; • // Sort the array by successive merges • while (partitionLen < array.length) • { • // Merge array, creating new array • array = mergePass(array, partitionLen); • partitionLen = partitionLen * 2; • } • return array; • } The mergeSort() method! Programming and Problem Solving With Java

  26. Searching an Array • Searching: Basic feature of any data structure • Two kinds of searching • Positional access: what's the value in a particular location? • Associative access: what the location of a particular value? • Arrays work great for positional access • Example: what's the name in location 24? • System.out.println(name[24]); • No predefined associative access for arrays in Java • Example: what's the location of "Smith" in the name array? Programming and Problem Solving With Java

  27. Searching an Array: Linear Search • Linear search with index cards • Start with the first card. If the number you're looking for is on the first card, stop-you've found it. • Stop if the number you're looking for is on the second card. • Continue looking through the remaining cards. Stop if you see the number you're looking for. • If you get to the last card without finding the number, then you know it isn't in the index cards. Programming and Problem Solving With Java

  28. Searching an Array: Linear Search • Linear search in Java • Start at one end • Keep checking elements until end of array or you find the element • "Quick and dirty" version (can't be used inline) • // linearSearch: Returns the location of itemToFind, or -1 if • // not found. • static int linearSearch(double[] array, double itemToFind) • { • for (int itemNum = 0; itemNum < array.length; itemNum++) • { • if (array[itemNum] == itemToFind) • { • return itemNum; • } • { • return -1; • } Programming and Problem Solving With Java

  29. Searching an Array: Linear Search • Linear Search in Java • Version that uses while statement (can be inlined) • // linearSearch: Returns the location of itemToFind, or -1 if • // not found. • static int linearSearch(double[] array, double itemToFind) • { • int itemNum = 0; • while (itemNum < array.length && array[itemNum] != itemToFind) • { • itemNum++; • } • if (itemNum == array.length) • { • return -1; • } • else • { • return itemNum; • } • } Note order of subconditions Programming and Problem Solving With Java

  30. Searching An Array: Sets Example • Can use array as basis for Set class (integers only) • Set operations Programming and Problem Solving With Java

  31. Searching An Array: Sets Example • Venn diagrams of Set operations Programming and Problem Solving With Java

  32. Searching An Array: Sets Example • Methods in the IntSet class • add(): Adds an element to a set. If the element is already in the IntSet, it is not added again. • remove(): Removes an element from an IntSet. • toString(): Returns a String version of the IntSet contents in standard format: {1, 3, 2} • isEmpty(): Returns true if the IntSet is empty, false otherwise. • isFull(): Returns true if the IntSet is full, false otherwise. • isMember(): Returns true if item is in the IntSet, false otherwise. • union(): Returns the union of the current IntSet and another IntSet. • intersection(): Returns the intersection of the current IntSet and another IntSet. • difference(): Returns the difference of the current IntSet and another IntSet. Programming and Problem Solving With Java

  33. Searching An Array: Sets Example • Example of using the IntSet class • // Finds the intersection of {1, 2} and {2, 3} • import IntSet; • class FindIntersection • { • public static void main(String[] args) • { • // Define two IntSets; each can store up to 10 values • IntSet x = new IntSet(10), y = new IntSet(10); • // Put values in the sets • x.add(1); • x.add(2); • y.add(2); • y.add(3); • // Find the intersection • IntSet result = x.intersection(y); • // Display the result • System.out.println("The intersection of " + x + " and " • + y + " is " + result); • } • } • Output • The intersection of {1, 2} and {2, 3} is {2} Programming and Problem Solving With Java

  34. Searching An Array: Sets Example • IntSet class in Java • Uses Debug.assert() (from appendix C) • import Debug; • public class IntSet • { • // Constructor: Initializes a new IntSet with the given • // maximum size • public IntSet(int maxSize) • { • numElements = 0; • data = new int[maxSize]; • } • // add: Adds an element to a set. If the element is already in • // the IntSet, it is not added again. Array must not • // be full. • public void add(int item) • { • Debug.assert(!isFull(), "IntSet is full"); • if (!isMember(item)) • { • data[numElements] = item; • numElements++; • } • } Programming and Problem Solving With Java

  35. Searching An Array: Sets Example • IntSet class in Java (continued) • // remove: Removes an element from a set. Does nothing if • // the element is not in the set. • public void remove(int item) • { • int itemNum = search(item); • if (itemNum != -1) • { • numElements--; • data[itemNum] = data[numElements]; • } • } • // isMember: Returns true if item is in the set, false otherwise • public boolean isMember(int item) • { • return search(item) != -1; • } Programming and Problem Solving With Java

  36. Searching An Array: Sets Example • IntSet class in Java (continued) • // search: Returns location of item or -1 if not there. • private int search(int item) • { • int itemNum = 0; • while (itemNum < numElements && data[itemNum] != item) • { • itemNum++; • } • if (itemNum == numElements) • { • return -1; • } • else • { • return itemNum; • } • } Linear search! Programming and Problem Solving With Java

  37. Searching An Array: Sets Example • IntSet class in Java (continued) • // toString: Returns a String version of the set's contents • // in standard format: {1, 3, 2} • public String toString() • { • String resultString = "{"; • for (int i = 0; i < numElements - 1; i++) • { • resultString = resultString + data[i] + ", "; • } • return resultString + data[numElements - 1] + "}"; • } • // isEmpty: Returns true if the set is empty, false otherwise • public boolean isEmpty() • { • return numElements == 0; • } • // isFull: Returns true if the set is full, false otherwise • public boolean isFull() • { • return numElements == data.length; • } Programming and Problem Solving With Java

  38. Searching An Array: Sets Example • IntSet class in Java (continued) • // union: Returns the union of the current set and anotherSet • public IntSet union(IntSet anotherSet) • { • // Assume no duplicates (worst case) and make the result set • // set large enough to hold everything from both sets • IntSet resultSet • = new IntSet(numElements + anotherSet.numElements); • // Copy items from this set to the resultSet • for (int i = 0; i < numElements; i++) • { • resultSet.add(data[i]); • } • // Copy elements from anotherSet to resultSet (The add() • // method will make sure that no element is added twice.) • for (int i = 0; i < anotherSet.numElements; i++) • { • resultSet.add(anotherSet.data[i]); • } • return resultSet; • } Programming and Problem Solving With Java

  39. Searching An Array: Sets Example • IntSet class in Java (continued) • // intersection: Returns the intersection of the current set • // and anotherSet • public IntSet intersection(IntSet anotherSet) • { • // Make the size of the resultSet the same as the smaller of • // this set and anotherSet (worst case, if all elements in • // smaller set are also in the larger one) • IntSet resultSet = new IntSet( • Math.min(numElements, anotherSet.numElements)); • // Put elements from this set in resultSet only if they are • // also in anotherSet • for (int i = 0; i < numElements; i++) • { • if (anotherSet.isMember(data[i])) • { • resultSet.add(data[i]); • } • } • return resultSet; • } Programming and Problem Solving With Java

  40. Searching An Array: Sets Example • IntSet class in Java (continued) • // difference: Returns the difference of the current set • // and anotherSet • public IntSet difference(IntSet anotherSet) • { • // Make the size of the resultSet the same as this set • // (worst case, if anotherSet has no elements in common • // with this one) • IntSet resultSet = new IntSet(numElements); • // Copy items from this set to the resultSet, but only • // if they aren't in anotherSet • for (int i = 0; i < numElements; i++) • { • if (!anotherSet.isMember(data[i])) • { • resultSet.add(data[i]); • } • } • return resultSet; • } • // IntSet variables • private int data[]; // Set data stored in an array • private int numElements; // Number of values in the array • } Programming and Problem Solving With Java

  41. Linear search vs. binary search Linear search fine for many applications Some applications need faster searching Binary search is much faster Requirement: array must be sorted Elements searched Searching an Array: Binary Search Programming and Problem Solving With Java

  42. Searching an Array: Binary Search • Binary search is like looking up a phone number • Start in middle of book • If name you're looking for comes before names on page, look in first half • Otherwise, look in second half Programming and Problem Solving With Java

  43. Searching an Array: Binary Search • Example of binary search: find 9.8 • Look in middle first • Can use either 3.1 or 5.2 as middle (but should always pick lower or upper when given a choice) • We'll always use the lower value as the middle Note that the array is sorted Programming and Problem Solving With Java

  44. Searching an Array: Binary Search • Example of binary search: find 9.8 (continued) • 9.8 greater than 3.1 • Therefore 9.8 can't appear in bottom half of array • Now look at middle of what's left: 7.4 Programming and Problem Solving With Java

  45. Searching an Array: Binary Search • Example of binary search: find 9.8 (continued) • 9.8 greater than 7.4 • Therefore 9.8 can't appear below 7.4 • Now look at middle of what's left: 9.8 Programming and Problem Solving With Java

  46. Searching an Array: Binary Search • Example of binary search: find 9.8 (continued) Programming and Problem Solving With Java

  47. Searching an Array: Binary Search • Binary search in Java - first version • // binarySearch: (First version - incomplete) Returns the location • // of itemToFind, or -1 if not found. The array must • // be sorted in ascending order. • static int binarySearch(double[] array, double itemToFind) • { • int bottom = 0; • int top = array.length - 1; • int middle = (bottom + top) / 2; • while (array[middle] != itemToFind) • { • if (array[middle] > itemToFind) • { • // Element must be in the lower half of the array • } • else • { • // Element must be in the upper half of the array • } • middle = (bottom + top) / 2; • } • // Return position or -1 if not there • } What goes here? Programming and Problem Solving With Java

  48. Searching an Array: Binary Search • Binary search in Java • Value we're looking for is in lower half of array • Example: Looking for 2.5 Programming and Problem Solving With Java

  49. Searching an Array: Binary Search • Binary search in Java • Value we're looking for is in upper half of array • Example: Looking for 5.2 Programming and Problem Solving With Java

  50. Searching an Array: Binary Search • Binary search in Java - second version • // binarySearch: (Second version - incomplete) Returns the location • // of itemToFind, or -1 if not found. The array must • // be sorted in ascending order. • static int binarySearch(double[] array, double itemToFind) • { • int bottom = 0; • int top = array.length - 1; • int middle = (bottom + top) / 2; • while (array[middle] != itemToFind) • { • if (array[middle] > itemToFind) • { • // Element must be in the lower half of the array • top = middle - 1; • } • else • { • // Element must be in the upper half of the array • bottom = middle + 1; • } • middle = (bottom + top) / 2; • } • // Return position or -1 if not there • } Doesn't work if itemToFind not in array What goes here? Programming and Problem Solving With Java

More Related