1 / 39

CSC 204 – Programming I

CSC 204 – Programming I. Searching & Sorting. 13.4 Sorting. One of the most fundamental operations on data is sorting: putting a list of items in order. Examples of sorted lists: Numbers: –53 –38 9 16 45 66 89 Characters: 0 1 A B a b

Download Presentation

CSC 204 – Programming I

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. CSC 204 – Programming I Searching & Sorting

  2. 13.4 Sorting • One of the most fundamental operations on data is sorting: putting a list of items in order. • Examples of sorted lists: Numbers: –53 –38 9 16 45 66 89 Characters: 0 1 A B a b Strings: aardvark ant anteater bat cat • In Java, the ordering of characters is based on their Unicode values. • Strings are normally sorted into lexicographic order.

  3. Ascending vs. Descending • Data items can be sorted into ascending order (with smaller values coming before larger ones), or descending order: Ascending order: –53 –38 9 16 45 66 89 Descending order: 89 66 45 16 9 –38 –53 • Sorting can be very time consuming if not done properly. • Fortunately, a number of good sorting algorithms are known.

  4. Inserting into a Sorted Array • An algorithm for inserting items into an empty array, keeping the items in sorted order at all times: 1. For all positions in the array, from 0 to n – 1 (where n is the number of items stored in the array), test whether the item to be inserted is less than the one stored at position i. If so, break out of the loop. 2. Insert the new item at position i after moving the items at positions i through n – 1 down one position.

  5. Inserting into a Sorted Array • The insertion algorithm expressed in Java: int i; for (i = 0; i < n; i++) if (itemToInsert < a[i]) break; for (int j = n; j > i; j--) a[j] = a[j-1]; a[i] = itemToInsert; n++; • This algorithm works even if the new item is larger than all the ones already in the array, or if the array contains no items at all.

  6. Inserting into a Sorted Array • If the array contains values other than numbers, the condition in the if statement will need to be changed. • The test condition if a contains strings: itemToInsert.compareTo(a[i])<0

  7. Inserting into a Sorted Array • The algorithm for inserting items into an array illustrates an important design principle: Design an algorithm to work in the typical case. Then go back and check to see if it correctly handles the special cases. If it doesn’t, add additional tests for those cases.

  8. Inserting into a Sorted Array • Snapshots of an array as the numbers 83, 24, 56, 90, and 17 are inserted:

  9. Insertion Sort • The idea of inserting a new item into a set of items that’s already in order can be used to sort an array even if all the items are already stored in the array prior to sorting. • An array a can be sorted by inserting the element at position i into the ones at positions 0 through i – 1 (which will already be in order).

  10. Insertion Sort • In other words: • Insert the element at position 1 into the elements at positions 0 through 0. • Insert the element at position 2 into the elements at positions 0 through 1. • Insert the element at position 3 into the elements at positions 0 through 2, and so on. • This sorting algorithm is known as insertion sort.

  11. Insertion Sort • The insertion sort algorithm is simpler if the element to be inserted (the one at position i) is compared with the elements at positions i – 1, i – 2, …, 0, working backward instead of forward. • If a comparison indicates that the element to be inserted is smaller than the one at position j, then the element at position j can be moved down one place in the array.

  12. Insertion Sort • An example that uses insertion sort to sort an array of five integers: Shaded elements are not yet in sorted order.

  13. Insertion Sort • A Java version of insertion sort: for (int i = 1; i < a.length; i++) { int itemToInsert = a[i]; int j = i - 1; while (j >= 0 && itemToInsert < a[j]) { a[j+1] = a[j]; j--; } a[j+1] = itemToInsert; }

  14. Insertion Sort • If the array contains values other than numbers, the condition in the while statement will need to be changed. • The while statement if a contains strings: while (j >= 0 && itemToInsert.compareTo(a[j]) < 0) { … }

  15. Insertion Sort • Insertion sort is easy to implement but not very efficient. • In the worst case, it performs 1 + 2 + 3 + … + (n – 1) = n(n – 1)/2 comparisons, where n is the number of elements in the array. • This number is approximately n2/2, so the time required to sort grows rapidly as n increases.

  16. Insertion Sort • Comparisons performed by insertion sort for various array sizes: Array Number of Size Comparisons 10 45 100 4,950 1,000 499,500 10,000 49,995,000 100,000 4,999,950,000 • For small arrays, insertion sort is usually fast enough. • For larger arrays, better algorithms are necessary.

  17. Program: Sorting a Series of Lines • The SortLines program will sort a series of lines entered by the user. • When the user enters a blank line, SortLines will display the lines entered by the user, sorted into lexicographic order.

  18. User Interface • An example: Enter lines to be sorted, ending with a blank line. To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; No more; and, by a sleep to say we end The heartache and the thousand natural shocks That flesh is heir to, 'tis a consummation Devoutly to be wish'd. To die, to sleep; To sleep: perchance to dream: ay, there's the rub; For in that sleep of death what dreams may come user enters a blank line

  19. User Interface • An example (continued): And by opposing end them? To die: to sleep; Devoutly to be wish'd. To die, to sleep; For in that sleep of death what dreams may come No more; and, by a sleep to say we end Or to take arms against a sea of troubles, That flesh is heir to, 'tis a consummation The heartache and the thousand natural shocks The slings and arrows of outrageous fortune, To be, or not to be: that is the question: To sleep: perchance to dream: ay, there's the rub; Whether 'tis nobler in the mind to suffer

  20. Program Design: SortLines • Because the number of lines isn’t known in advance, a vector would be a good data structure. • The lines are read one by one, so they can be inserted into the vector so that it remains sorted at all times. • The insertElementAt method will automatically shift existing elements to make room for the new one.

  21. SortLines.java // Sorts a series of lines entered by the user import java.util.*; import jpb.*; public class SortLines { public static void main(String[] args) { // Prompt user to enter lines System.out.println("Enter lines to be sorted, " + "ending with a blank line."); // Create vector to store lines Vector v = new Vector();

  22. // Read lines and insert into vector; elements will be // kept in order at all times while (true) { // Read a line; exit loop if line is empty String inputLine = SimpleIO.readLine(); if (inputLine.length() == 0) break; // Determine where line should be stored in vector int i; for (i = 0; i < v.size(); i++) if (inputLine.compareTo((String) v.elementAt(i)) < 0) break; // Insert line at this position. Existing elements will // be moved to make room for the new element. v.insertElementAt(inputLine, i); } // Display elements of vector for (int i = 0; i < v.size(); i++) System.out.println(v.elementAt(i)); } }

  23. Reading lines from a file try { FileReader fileIn = new FileReader(filename); BufferedReader in = new BufferedReader(fileIn);   int index = 0; String line; while ( index < A.length ){ line = in.readLine(); if (line == null) break; lines[index++] = line; } in.close(); }catch (IOException e){ System.out.println(e.getMessage()); }

  24. On-line Resources • The Java Tutorials at SUN’s website • http://java.sun.com/docs/books/tutorial/essential/io/overview.html

  25. 13.5 Searching • If the elements of an array (or vector) aren’t in any particular order, there is no better way to search for a particular element than sequential search. • If the elements are sorted, a more efficient strategy, binary search, becomes possible.

  26. Binary Search • Suppose that a is a sorted array and key is the value to be located in the array. • The binary search algorithm compares key with the element in the middle of a. • If key is smaller than the middle element, the algorithm can limit its search to the first half of a. • If key is larger, the algorithm searches only the last half of a. • This process is repeated until the key is found or there are no elements left to search.

  27. Binary Search • The binary search algorithm will use variables named low and high that keep track of which array elements are still under consideration. • A third variable, mid, will indicate the halfway point between low and high.

  28. Binary Search • A Java version of the binary search algorithm: int low = 0; int high = a.length - 1; while (low < high) { int mid = (low + high) / 2; if (a[mid] < key) low = mid + 1; else high = mid; }

  29. Binary Search • If a contains values other than numbers, the condition in the if statement will need to be changed. • If the elements of a are strings, the statement becomes if (a[mid].compareTo(key) < 0) …

  30. Binary Search • If the key is present in the array, the final value of low indicates its position in the array. • If the key isn’t known to be present in the array, an additional test will be needed after the while loop terminates: if (a[low] == key) // Key was found else // Key was not found

  31. Binary Search • A binary search for the number 40:

  32. Binary Search • Binary search works by repeatedly dividing the array in half, so it is extremely efficient. • In the worst case, it performs log2n comparisons, rounded up to the nearest integer, where n is the number of elements in the array.

  33. Binary Search • The number of comparisons performed by binary search remains small even for very large values of n, because log2n is such a slow-growing function. Array Number of Size Comparisons 10 4 100 7 1,000 10 10,000 14 100,000 17

  34. Program: Determining Air Mileage • The AirMileage program will display the air mileage from New York City to an international city specified by the user: This program finds the air mileage between New York and major international cities. Enter city name: Oslo Oslo is 3671 miles from New York City.

  35. Program Design: AirMileage • The AirMileage program will store the names of 36 cities in an array. • A parallel array will store the distances from New York to each of the cities in the first array. • Using binary search to locate the city name entered by the user will be more efficient than using sequential search.

  36. AirMileage.java import jpb.*; public class AirMileage { // Names of international cities private static final String[] CITY_NAMES = {"acapulco", "amsterdam", "antigua", "aruba", "athens", "barbados", "bermuda", "bogota", "brussels", "buenos aires", "caracas", "copenhagen", "curacao", "frankfurt", "geneva", "glasgow", "hamburg", "kingston", "lima", "lisbon", "london", "madrid", "manchester", "mexico City", "milan", "nassau", "oslo", "paris", "reykjavik", "rio de janeiro", "rome", "san juan", "santo domingo", "st. croix", "tel aviv", "zurich"};

  37. // Distances from New York to other cities private static final int[] DISTANCES = {2260, 3639, 1783, 1963, 4927, 2100, 771, 2487, 3662, 5302, 2123, 3849, 1993, 3851, 3859, 3211, 3806, 1583, 3651, 3366, 3456, 3588, 3336, 2086, 4004, 1101, 3671, 3628, 2600, 4816, 4280, 1609, 1560, 1680, 5672, 3926}; public static void main(String[] args) { // Display initial message System.out.println( "This program finds the air mileage between\n" + "New York and major international cities.\n"); // Prompt user for city name SimpleIO.prompt("Enter city name: "); String cityName = SimpleIO.readLine().trim();

  38. // Use binary search to locate name in CITY_NAMES array int i = binarySearch(CITY_NAMES, cityName.toLowerCase()); // If name was found in array, display distance from New // York to chosen city if (cityName.equalsIgnoreCase(CITY_NAMES[i])) System.out.println(cityName + " is " + DISTANCES[i] + " miles from New York City."); else System.out.println(cityName + " wasn't found."); }

  39. // Uses the binary search algorithm to locate key in the // array a. Returns the index of key if it is found in a. private static int binarySearch(String[] a, String key) { int low = 0; int high = a.length - 1; while (low < high) { int mid = (low + high) / 2; if (a[mid].compareTo(key) < 0) low = mid + 1; else high = mid; } return low; } }

More Related