370 likes | 482 Views
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.
E N D
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 • 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
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; • }
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.
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
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
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
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
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);
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
Row Column Accessing 2D Array • Requires two indices • Which cell is MILEAGE_CHART [3][2]?
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.
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 ] } }
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
“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
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;
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()
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)
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
How the methods work • set • replaces value of Object parameter at the given index • size is not changed
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
Examples ArrayList club = new ArrayList(); club.add(“Spanky”); club.add(“Darla”); club.add(“Buckwheat”); System.out.print(club); Displays: [Spanky, Darla, Buckwheat]
Examples //using club from previous slide club.set(1, “Mikey”); System.out.print(club); Displays: [Spanky, Mikey, Buckwheat]
Examples //using club from previous slide club.add(0, club.remove(club.size()-1)); System.out.print(club); Displays: [Buckwheat, Spanky, Mikey]
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]
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]
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!!
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
public boolean hasNext() • Returns true if the iteration has more elements • Ex: while(it.hasNext()) //do something
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 }
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(); }
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?
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
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?
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");
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( );