1 / 37

Java Programming

Java Programming. Advanced Array Concepts Chapter 9. Sorting Arrays. Sorting Process of arranging series of objects in some logical order Ascending order Begin with object that has lowest value Descending order Start with object that has largest value. Sorting Arrays.

gauri
Télécharger la présentation

Java Programming

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. Java Programming Advanced Array Concepts Chapter 9

  2. Sorting Arrays • Sorting • Process of arranging series of objects in some logical order • Ascending order • Begin with object that has lowest value • Descending order • Start with object that has largest value

  3. Sorting Arrays • Simplest possible sort • Involves two values that are out of order • Swap two values {16, 2} → {2, 16} temp = valA; // 16 goes to temp valA = valB; // 2 goes to valA valB = temp; // 16 goes to valB

  4. Sorting Arrays • Bubble sort • Continue to compare pairs of items • Swapping them if they are out of order • for(int a = 0; a < myList.length - 1; a++) • for(int b = 0; b < myList.length - 1; b++) • if (myList[b] > myList[b+1]) { • temp = myList[b]; • myList[b] = myList[b+1]; • myList[b+1] = temp; • }

  5. Sorting Arrays • Selection sort • Finds the smallest number in the list and places it first. It then finds the smallest number remaining and places it next to first, and so on until the list contains only a single number. • Can also find the largest number in the list and place it last.

  6. Selection Sort • Make passes through the list (or part of it) • on each pass select one item (smallest or largest) to be correctly position • exchange that item with the one that was in its place

  7. Selection Sort • On successive passes • must only check beyond where smallest item has been placed • A pair of nested for() loops will accomplish this checking and swapping of values • Note: this is a simple but inefficient algorithm

  8. Linear Insertion Sort • As list is built, keep it sorted • always place a new value in the list where it belongs • Tasks include • finding where the new item belongs • shifting all elements from that slot and beyond over one slot • inserting the new item in the vacated spot • Again, a double nested loop can accomplish this task • This is efficient for small lists 49

  9. Quicksort • Very efficient • Implemented by a recursive algorithm • Strategy • choose a pivot point • perform exchanges so all elements to the left are less than the pivot • all elements on the right are greater • this makes 2 sub lists where the same strategy with the pivot can be performed (repeatedly) • this is a "divide and conquer" concept

  10. Sorting Arrays • Since sorting is frequently used in programming, Java provides several overloaded sort methods for sorting an array of int, double, char, short, long, and float in the java.util.Arrays class. • For example, the following code sorts an array of numbers and an array of characters. double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5}; java.util.Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'}; java.util.Arrays.sort(chars);

  11. Two Dimensional Arrays • Many data types are in a table format • Need two indices to access elements of the table • Row and column • myList [a][b] • Also possible to have higher dimensional arrays • n-dimensional array requires nindeces

  12. Row Column Accessing 2D Array • Requires two indices • Which cell is MILEAGE_CHART [3][2]?

  13. Two Dimensional Arrays • In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations. • If m is a 2-D array, then myList[k] is a 1-D array, the k-th row. • myList.lengthis the number of rows. • myList[k].length is the length of the k-th row.

  14. Two Dimensional Arrays • A 2-D array can be traversed using nested loops: • Number of rows is myList.length • Number of columns is myList[0].length for (intr = 0; r < myList.length; r++) { for (int c = 0; c < myList[0].length; c++) { ... // process myList[ r ][ c ] } }

  15. Ragged Array • Java allows “ragged” arrays, in which different rows have different lengths. • In a rectangular array, m[0].length can be used to represent the number of columns. “Ragged” array: Rectangular array: m.length m.length m[3].length m[0].length

  16. “Triangular” Loops • “Transpose a matrix” idiom: int n = m.length; for (intr = 1; r < n; r++) { for (int c = 0; c < r; c++) { double temp = m [ r ][ c ]; m [ r ][ c ] = m [ c ][ r ]; m [ c ][ r ] = temp; } } The total number of iterations through the inner loop is: 1 + 2 + 3 + ... + (n-1) = n (n - 1) / 2

  17. Array Class • Recall that arrays represent a class of objects • We used shortcut notation as a convenience to bypass the class • The array class has useful tools import java.util.Arrays; import java.util.ArrayList;

  18. Methods • ArrayList() //constructor • void add(int index, Object x) • boolean add(Object x) • Object set(int index, Object x)               • Object remove(int index) • int size () • Object get(int index)   • Iterator iterator()                 

  19. How the methods work • add: • boolean add(Object x) – inserts the Object x at the end of the list (size increases by 1), returns true • void add(int index, Object x) – inserts the Object x at the given index position (elements will be shifted to make room and size increases by 1)

  20. How the methods work • get: • returns the Object at the specified index • should cast when using value returned • throws IndexOutOfBoundsException if index<0 or index>=size

  21. How the methods work • set • replaces value of Object parameter at the given index • size is not changed

  22. How the methods work • remove • removes the element at the specified index • throws IndexOutOfBoundsException if index<0 or index>=size • size will be decreased by 1 • returns Object removed

  23. Examples ArrayList club = new ArrayList(); club.add(“Spanky”); club.add(“Darla”); club.add(“Buckwheat”); System.out.print(club); Displays: [Spanky, Darla, Buckwheat]

  24. Examples //using club from previous slide club.set(1, “Mikey”); System.out.print(club); Displays: [Spanky, Mikey, Buckwheat]

  25. Examples //using club from previous slide club.add(0, club.remove(club.size()-1)); System.out.print(club); Displays: [Buckwheat, Spanky, Mikey]

  26. Examples //ArrayLists only contain Objects!! ArrayList odds = new ArrayList(); for(inti=1; i<10; i+=2) odds.add(new Integer(i)); System.out.println(odds); Displays: [1, 3, 5, 7, 9]

  27. Examples //ArrayLists only contain Objects!! ArrayList odds = new ArrayList(); for(inti=1; i<10; i+=2) { Integer x = new Integer(i); odds.add(x);} System.out.println(odds); Displays: [1, 3, 5, 7, 9]

  28. Objects and Casting //Casting when pulling out from ArrayList ArrayList names = new ArrayList(); names.add("Clint"); names.add("John"); names.add("Robert"); names.add("Henry"); Object obj = names.get(2); //ok System.out.println( obj.toString() ); String str1 = names.get(3); //syntax error String str2 = (String)(names.get(4)); //ok char c = ((String)(names.get(0))).charAt(0); //Gack!!

  29. How the methods work • iterator • returns an Iterator object • Iterators allow all of the Objects in the list to be accessed one by one, in order • methods for an Iterator object • hasNext • next • remove

  30. public boolean hasNext() • Returns true if the iteration has more elements • Ex: while(it.hasNext()) //do something

  31. public Object next() • Returns the next element in the iteration • Each time this method is called the iterator “moves” • Ex: while(it.hasNext()) { Object obj = it.next(); if( //obj meets some condition) //do something }

  32. public void remove() • Removes from the collection the last element returned by the iterator • Can be called only once per call to next while(it.hasNext()) { Object obj = it.next(); if( //obj meets some condition) it.remove(); }

  33. Remove Example public void removeAllLength(ArrayListli, intlen) { //pre: li contains only String objects //post: all Strings of length = len removed //right way String temp; for(inti = li.size()-1; i < 0; i--) { if( temp.length() == len ) li.remove(i); } } What if the list contains ["hi", "ok", "the", "so", "do"] and len = 2?

  34. Remove Example public void removeAllLength(ArrayListli, intlen) { //pre: li contains only String objects //post: all Strings of length = len removed //wrong way String temp; for(inti = 0; i < li.size(); i++) { temp = (String)li.get(i); if( temp.length() == len ) li.remove(i); } } Problem with this code: Note that the index of each subsequent value changes

  35. Remove Example public void removeAllLength(ArrayListli, intlen) { //pre: li contains only String objects //post: all Strings of length = len removed //right way using iterator String temp; iterator it = li.iterator(); while( it.hasNext() ) { temp = (String)li.next(); if( temp.length() == len ) it.remove(); } } What if the list contains ["hi", "ok", "the", "so", "do"] and len = 2?

  36. Searching • Linear search • begin with first item in a list • search sequentially until desired item found or reach end of list • Binary search (of a sorted list) • look at middle element • if target value found, done • if target value is higher, look in middle of top half of list • if target value is lower, look in middle of lower half of list position = Arrays.binarySearch(myList, "Tim");

  37. Clone • Recall that the array references a memory address • copy = myList still references the same memory • Any changes done to copy also changes myList • We can make a copy by populating element by element • We can also make a copy by using the clone method in the Arrays class copy = myList.clone( );

More Related