Chapter 7 Single-Dimensional Arrays

Similar documents
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

CS1150 Principles of Computer Science Arrays

Chapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CS115 Principles of Computer Science

CS1150 Principles of Computer Science Arrays

Module 7: Arrays (Single Dimensional)

Java-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

14. Array Basics. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Lecture #8-10 Arrays

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Passing Array to Methods

Java, Arrays and Functions Recap. CSE260, Computer Science B: Honors Stony Brook University

Recapitulate CSE160: Java basics, types, statements, arrays and methods

array Indexed same type

Chapter 6 Single-dimensional Arrays

15. Arrays and Methods. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

Arrays. Eng. Mohammed Abdualal

Lecture 6 Sorting and Searching

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 171: Introduction to Computer Science II. Arrays. Li Xiong

Object Oriented Programming. Java-Lecture 6 - Arrays

Computer programming Code exercises [1D Array]

Last Class. More on loops break continue A bit on arrays

Computer Science is...

Objectives of the lesson

Declaring Array Variable

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

16. Searching and Sorting

Chapter 7 Multidimensional Arrays

Chapter 7 Arrays and Vectors

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Chapter 8 Multi-Dimensional Arrays

Java is an objet-oriented programming language providing features that support

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Chapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer?

Data Types. Operators, Assignment, Output and Return Statements

Research Group. 3: Loops, Arrays

Introduction to Programming Using Java (98-388)

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Computer Programming, I. Laboratory Manual. Final Exam Solution

Array. Prepared By - Rifat Shahriyar

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Introduction to Java & Fundamental Data Types

Computer Science II (20082) Week 1: Review and Inheritance

Chapter 2. Elementary Programming

Chapter 7: Arrays and the ArrayList Class

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Chapter 8 Multidimensional Arrays

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Lecture #6-7 Methods

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Example: Computing prime numbers

What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Top-down programming design

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

Java Programming: Program Design Including Data Structures. Chapter Objectives

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Pace University. Fundamental Concepts of CS121 1

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

C/C++ Programming Lecture 18 Name:

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

CS1150 Principles of Computer Science Loops (Part II)

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

CS2141 Software Development using C/C++ C++ Basics

Lecture 7: Searching and Sorting Algorithms

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

ARRAYS and ARRAYLISTS

Spring 2010 Java Programming

Array basics. Readings: 7.1

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Multidimensional Arrays. CSE 114, Computer Science 1 Stony Brook University

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

CS 112 Introduction to Programming

Sorting and searching arrays

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

CS2401 QUIZ 5 February 26, questions / 20 points / 20 minutes NAME:..

Arrays in Java Using Arrays

Example. Password generator

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

Chapter Objectives. List Processing. Chapter 10: Applications of Arrays and Strings. Java Programming: Program Design Including Data Structures

Transcription:

Chapter 7 Single-Dimensional Arrays 1

Arrays Array is a data structure that represents a collection of same-types data elements. A single-dimensional array is one that stores data elements in one row. myarray: Strings are arrays. String Name = "John Smith"; 0 1 2 3 4 5 6 7 6 4 1 9 7 3 2 8 String coursenumber; coursenumber = new String ("CS 1301"); 2

Declaring Array Variables datatype[] arrayrefvar; Example: double[] mylist; int[] yourlist; boolean[] herlist; char[] hislist; //vs. double mylist; datatype arrayrefvar[]; // This style is allowed, but not preferred Example: double mylist[]; 3

Creating Arrays This is to allocate memory space for the array. arrayrefvar = new datatype[arraysize]; Example: mylist = new double[10]; yourlist = new int[100]; herlist = new boolean[20]; hislist = new char[500]; mylist[0] references the first element in the array. mylist[9] references the last element in the array. In one step you can declare and create: double[] mylist = new double[10]; 4

The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayrefvar.length; (not length()as with strings) For example, int length = mylist.length; // returns 10 int length = yourlist.length; // returns 100; int length = herlist.length; // returns 20; int length = hislist.length; // returns 500; 5

Array Representation double[] mylist = new double[10]; mylist reference mylist[0] 5.6 mylist[1] 4.5 Array reference variable mylist[2] mylist[3] 3.3 13.2 Array element at index 5 mylist[4] mylist[5] mylist[6] 4.2 34.33 34.7 Element value mylist[7] 45.45 mylist[8] 99.993 mylist[9] 111.23 6

Default Values When an array is created, its elements are assigned the default value of 0 for the numeric primitive types (byte, short, int, long) 0.0 for the numeric primitive data types (float, double) '\u0000' false for char types (Null value) for boolean type. 7

Indexed Variables The array elements are accessed through the index. The array indices start from 0 to arrayrefvar.length-1 Example: double[] mylist = new double[5]; Array mylist holds five double values The indices are 0 to 4. Each element in the array is represented using the following syntax, known as an indexed variable: arrayrefvar[index]; mylist[0]= 25.7; //value in first element double price = mylist[3]; 8

Using Indexed Variables After an array is created, an indexed variable can be used in the same way as a regular variable is used. Example: The following code adds the values in the first and second positions in array mylist and stores the result in the third position. mylist[2] = mylist[0] + mylist[1]; Example: The following code prints out the content of array mylist. for (int i = 0; i <= mylist.length-1; i++) System.out.println("Value in position " + i + " = " + mylist[i]); 9

Array Initialization Declaring, creating, initializing in one step: double[] mylist = {1.9, 2.9, 3.4, 3.5; int[] numbergrades = {70, 65, 87, 93, 90; char[] lettergrades = {'C', 'D', 'B', 'A', 'A'; boolean[] myflags = {true, false, true, false; This shorthand notation is equivalent to the following statements: double[] mylist = new double[4]; mylist[0] = 1.9; mylist[1] = 2.9; mylist[2] = 3.4; mylist[3] = 3.5; Be Careful! This code gives an error. It must be in one statement. int[] numbergrades; numbergrades = {70, 65, 87, 93, 90; 10

animation Trace Program with Arrays Declare array variable values, create an array, and assign its reference to values public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the array is created 0 0 1 0 2 0 3 0 4 0 11

animation Trace Program with Arrays i becomes 1 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the array is created 0 0 1 0 2 0 3 0 4 0 12

animation Trace Program with Arrays i (=1) is less than 5 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the array is created 0 0 1 0 2 0 3 0 4 0 13

animation Trace Program with Arrays After this line is executed, value[1] is 1 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the first iteration 0 0 1 1 2 0 3 0 4 0 14

animation Trace Program with Arrays After i++, i becomes 2 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the first iteration 0 0 1 1 2 0 3 0 4 0 15

animation Trace Program with Arrays i (= 2) is less than 5 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the first iteration 0 0 1 1 2 0 3 0 4 0 16

animation Trace Program with Arrays After this line is executed, values[2] is 3 (2 + 1) public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the second iteration 0 0 1 1 2 3 3 0 4 0 17

animation Trace Program with Arrays After this, i becomes 3. public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the second iteration 0 0 1 1 2 3 3 0 4 0 18

animation Trace Program with Arrays i (=3) is still less than 5. public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the second iteration 0 0 1 1 2 3 3 0 4 0 19

animation Trace Program with Arrays After this line, values[3] becomes 6 (3 + 3) public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the third iteration 0 0 1 1 2 3 3 6 4 0 20

animation Trace Program with Arrays After this, i becomes 4 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the third iteration 0 0 1 1 2 3 3 6 4 0 21

animation Trace Program with Arrays i (=4) is still less than 5 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the third iteration 0 0 1 1 2 3 3 6 4 0 22

animation Trace Program with Arrays After this, values[4] becomes 10 (4 + 6) public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the fourth iteration 0 0 1 1 2 3 3 6 4 10 23

animation Trace Program with Arrays After i++, i becomes 5 public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the fourth iteration 0 0 1 1 2 3 3 6 4 10 24

animation Trace Program with Arrays i ( =5) < 5 is false. Exit the loop public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; After the fourth iteration 0 0 1 1 2 3 3 6 4 10 25

animation Trace Program with Arrays After this line, values[0] is 11 (1 + 10) public class Test { public static void main(string[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; values[0] = values[1] + values[4]; 0 1 2 3 4 11 1 3 6 10 26

Some common examples: Processing Arrays 1. (Initializing arrays with input values) 2. (Initializing arrays with random values) 3. (Printing arrays) 4. (Summing all elements) 5. (Finding the largest element) 6. (Finding the smallest index of the largest element) 7. (Random shuffling) 8. (Shifting elements) 27

Initializing arrays with input values... //Some code double[] mylist = new double[5]; java.util.scanner input = new java.util.scanner(system.in); System.out.print("Enter " + mylist.length + " double values: "); for (int i = 0; i < mylist.length; i++) mylist[i] = input.nextdouble();... //other code 28

Initializing arrays with random values... //Some code double[] mylist = new double[5];... //initialize the array for (int i = 0; i < mylist.length; i++) mylist[i] = Math.random() * 100; //double type... //other code 29

Printing arrays... //Some code double[] mylist = new double[5];... //initialize the array for (int i = 0; i < mylist.length; i++) System.out.print(myList[i] + " ");... //other code 30

Summing all elements... //Some code double total = 0; double[] mylist = new double[5];... //initialize the array for (int i = 0; i < mylist.length; i++) total = total + mylist[i];... //other code 31

Finding the largest element... //Some code double[] mylist = new double[5]; double max = mylist[0]; for (int i = 1; i < mylist.length; i++) { if (mylist[i] > max) max = mylist[i];... //other code 32

Random shuffling for (int i = 0; i < mylist.length; i++) { // Generate an index j randomly int index = (int)(math.random() * mylist.length); i mylist [0] [1] // Swap mylist[i] with mylist[j] double temp = mylist[i]; mylist[i] = mylist[index]; mylist[index] = temp; [index] A random index... swap 33

Shifting Elements double temp = mylist[0]; // Retain the first element // Shift elements left for (int i = 1; i < mylist.length; i++) { mylist[i - 1] = mylist[i]; mylist // Move the first element to fill in the last position mylist[mylist.length - 1] = temp; 34

Enhanced for Loop (for-each loop) JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array mylist: int[] mylist = new int[5];... for (int value: mylist) System.out.println(value); In general, the syntax is For (elementtype value: arrayrefvar) { // Process the value You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. 35

Copying Arrays For object references, an assignment statement copies the memory address NOT the array content: Before: name1 name2 "Steve Jobs" "Steve Wozniak" name2 = name1; After: name1 name2 "Steve Jobs" 36

Copying Arrays Use a loop: int[] sourcearray = {2, 3, 1, 5, 10; int[] targetarray = new int[sourcearray.length]; for (int i = 0; i < sourcearrays.length; i++) targetarray[i] = sourcearray[i]; 37

The arraycopy Utility arraycopy(sourcearray, src_pos, targetarray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetarray, 0, sourcearray.length); This will copy every element in sourcearray to targetarray. Must create targetarray first. System.arraycopy(sourceArray, 10, targetarray, 10, length); This will copy every element in sourcearray to targetarray starting at position 10. Must create targetarray first. 38

Passing Arrays to Methods public static void printarray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); Invoke the method: int[] list = {3, 1, 2, 6, 4, 2; printarray(list); Invoke the method again: printarray(new int[]{3, 1, 2, 6, 4, 2); Anonymous (nameless) array 39

The statement Anonymous Array printarray(new int[]{3, 1, 2, 6, 4, 2); creates un-named array and pass it to method printarray(). There is no explicit reference variable for the this array. Such array is called an anonymous array. 40

Pass By Value - Revisited Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. 41

Simple Example public class Test { public static void main(string[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y is an array of int values mymethod(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); public static void mymethod(int number, int[] numbers) { number = 1001; // Assign a new value to number, locally numbers[0] = 5555; // Assign a new value to numbers[0] 42

Call (Run-Time) Stack Stack Heap Space required for method mymethod int[] numbers: reference int number: 1 Space required for the main method int[] y: reference int x: 1 0 0 0 The arrays are stored in a heap. Array of ten int values is stored here When invoking mymethod(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array (memory address), numbers now contains the same reference value to the same array. 43

Call (Run-Time) Stack Stack Space required for method mymethod int[] numbers: reference int number: 1001 Space required for the main method int[] y: reference int x: 1 Heap 5555 0 0 The arrays are stored in a heap. Array of ten int values is stored here 44

Call (Run-Time) Stack Heap Space required for the main method int[] y: reference int x: 1 5555 0 0 The arrays are stored in a heap. 45

Variable-Length Parameter List Java allows a method to take variables number of parameters of the same type. The parameter list is treated as an array. public class VarArgsDemo { public static void main (String[] args) { printmax(50, 29, 19, 2, 98, 16); printmax(150, 300, 275); printmax(new int[] {1,2,3,4,5,6); public static void printmax(int... numbers) { if (numbers.length == 0) { System.out.println("No arguments passed! "); return; // to exit the method, not to return a value int result = numbers[0]; for (int i=1; i<numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); 46

Searching Arrays Searching is the process of looking for a specific element in an array. The element may be found or may not. How? Two commonly used methods are: - linear search: search all elements in sequence from first to last. - binary search: search an ordered array taking into consideration one-half of the array in each stop. 47

Linear Search The linear search approach compares the key element, key or target, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1. public class LinearSearch { /** The method for finding a key in the list */ public static int linearsearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) [0] [1] [2] return i; list return -1; key Compare key with list[i] for i = 0, 1, 48

animation Linear Search Animation Key 3 3 3 3 3 3 List 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 49

Binary Search For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g.: 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the array. If the key is less than the middle element, you only need to search the key in the first half of the array. If the key is equal to the middle element, the search ends with a match. If the key is greater than the middle element, you only need to search the key in the second half of the array. 50

animation Binary Search Key 8 8 8 List 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 51

Binary Search, cont. key is 11 low mid high key < 50 list [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 2 4 7 10 11 45 50 59 60 66 69 70 79 low mid high key > 7 list [0] [1] [2] [3] [4] [5] 2 4 7 10 11 45 low mid high key == 11 list [3] [4] [5] 10 11 45 52

key is 54 key > 50 Binary Search, cont. [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] list low mid high 2 4 7 10 11 45 50 59 60 66 69 70 79 low mid high key < 66 key < 59 list list [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 59 60 66 69 70 79 low mid high [7] [8] 59 60 low high [6] [7] [8] 59 60 53

The Solution /** Use binary search to find the key in the list */ public static int binarysearch(int[] list, int key) { int low = 0; int high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; // middle element if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; // target is found else low = mid + 1; return -1 - low; // target not found! 54

Class Arrays Since binary search is frequently used in programming, Java provides several overloaded binarysearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.arrays class. For example: import java.util.*; int[] list = {2,4,7,10,11,45,50,59,60,66,69,70,79; System.out.println("Index of value 11 is " + Arrays.binarySearch(list, 11)); char[] chars = {'a','c','g','x','y','z'; System.out.println("Index of letter t is " + Arrays.binarySearch(chars, 't')); Note: This call returns 4 (insertion point is 3, so return is -3-1) For the binarysearch method to work, the array must be pre-sorted in increasing order. See section 7.12, page 272, for other methods. (Arrays.sort, Arrays.equals, Arrays.fill, Arrays.toString) 55

Sorting Arrays Sorting, like searching, is also a common task in computer programming. Many different algorithms have been developed for sorting. This section introduces algorithm selection sort. 56

Selection Sort Selection sort finds the smallest number in the list and places it first. It then finds the smallest number remaining and places it second, and so on until the list contains only a single number. 57

The Algorithm for (int i = 0; i < list.length; i++) { // select the smallest element in list[i..listsize-1]; // swap the smallest with list[i], if necessary; // list[i] is in its correct position. // The next iteration apply on list[i..listsize-1] list[0] list[1] list[2] list[3]... list[0] list[1] list[2] list[3]... list[0] list[1] list[2] list[3]... list[0] list[1] list[2] list[3]... list[0] list[1] list[2] list[3]... list[10] list[10] list[10] list[10] list[10]... list[0] list[1] list[2] list[3]... list[10] 58

The Code /** The method for sorting the numbers */ public static void selectionsort(double[] list) { for (int i = 0; i < list.length; i++) { // Find the minimum in the list[i..list.length-1] double currentmin = list[i]; int currentminindex = i; for (int j = i + 1; j < list.length; j++) { if (currentmin > list[j]) { currentmin = list[j]; currentminindex = j; // Swap list[i] with list[currentminindex] if necessary; if (currentminindex!= i) { list[currentminindex] = list[i]; list[i] = currentmin; 59

Arrays.sort Method 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. import java.util.*; double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5; Arrays.sort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'; Arrays.sort(chars); 60

Arrays.toString(list) Method Method Arrays.toString(list) method can be used to return a string representation for the list. import java.util.*; char[] chars = {'a', 'A', '4', 'F', 'D', 'P'; Arrays.sort(chars); //sort the list //print the list for (int i = 0; i < chars.length; i++) System.out.print(chars[i]+ " "); System.out.println(); //convert array to string String mystring = Arrays.toString(chars); System.out.println (mystring); Output: 4 A D F P a [4, A, D, F, P, a] 61

Passing Arguments to Main Method You can call a regular method by passing actual parameters. Can you pass arguments to main? Of course, yes. For example, the main method in class B is invoked by a method in A, as shown below: public class A { public static void main(string[] args) { String[] strings = {"New York", "Boston", "Atlanta"; B.main(strings); class B { public static void main(string[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); class B { public static vo for (int i = 0 System.out.p 62

End of Chapter 7 63