Introduction to Programming (CPSC 124)
—Hobart & William Smith Colleges, Fall 2014
Class Notes—October 24, 2014
Home | Syllabus | Calendar | Class Notes | Labs and Projects | General Notes |

Method Definitions and Arrays

Code Example from Class

/** * An example of developing algorithms and using methods as part of * "delaying concerns" to build more complex things. Selection sort * can be written more efficiently than this and without copying any * arrays at all, but getting something to work - and having a * manageable way to achieve that goal - is a good starting point. */ public class Sort { /** * Find the smallest element in the array. * * @param array array to search * @return the smallest element in 'array' */ public static int findSmallest ( int[] array ) { // 'min' is the smallest value found so far int min = array[0]; // go through the array // for each element, compare to the smallest so far (update as needed) for ( int i = 0 ; i < array.length ; i++ ) { if ( array[i] < min ) { min = array[i]; } } // 'min' is now the smallest value in the whole array return min; } /** * Return a copy of the array with the specified element removed. * * @param array the array * @param toremove the element to remove * @return a copy of the array with 'toremove' removed */ public static int[] eliminate ( int[] array, int toremove ) { int[] copy = new int[array.length-1]; // go through 'array', copying everything except 'toremove' // 'from' is the current index in array, 'to' is the current index // where array[from] will be copied to in 'copy' for ( int from = 0, to = 0 ; from < array.length ; from++ ) { // deal with duplicates - if there is more than one element in the // array with the value 'toremove', only the first one is skipped // when copying (we can tell if we've skipped yet by whether 'to' // is still the same as 'from') if ( array[from] != toremove || to != from ) { copy[to] = array[from]; to++; } } return copy; } /** * Return a sorted version of the array numbers. 'numbers' is not * changed! */ public static int[] sort ( int[] numbers ) { // a new array to hold the sorted result int[] sorted = new int[numbers.length]; int[] numbersleft = numbers; // the numbers not yet sorted // fill in the new array with things in the right order: // repeat for as many things are there are for ( int i = 0 ; i < numbers.length ; i++ ) { // find the smallest thing left int smallest = findSmallest(numbersleft); // write it as the next thing in the result sorted[i] = smallest; // remove the smallest from the things that are left numbersleft = eliminate(numbersleft,smallest); } return sorted; } public static void main ( String[] args ) { int[] a = { 10, 20, 5, 3, 15, 3, 7 }; int[] b = sort(a); // print out b to see if sorting worked for ( int i = 0 ; i < b.length ; i++ ) { System.out.print(b[i]+" "); } System.out.println(); } }

John Lasseter