Arrays.

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Multidimensional arrays Many problems require information be organized as a two- dimensional or multidimensional list Examples –Matrices –Graphical animation.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 Arrays Chapter 8 Spring 2007 CS 101 Aaron Bloomfield.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Arrays Chapter 8 Spring 2006 CS 101 Aaron Bloomfield.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Arrays Spring 2006 UVA - CS 101 Aaron Bloomfield Edited for WLCS by Paul Bui.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional 
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Arrays. 2 Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional 
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Arrays Chapter 7.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 6: Using Arrays.
EGR 2261 Unit 10 Two-dimensional Arrays
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 8 Arrays Objectives
CS 213: Data Structures and Algorithms
Building Java Programs Chapter 7
Nested Loop Review and Two-Dimensional Arrays
7 Arrays.
Arrays Continued.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 5 Arrays Introducing Arrays
EKT150 : Computer Programming
Chapter 8 Fall 2006 CS 101 Aaron Bloomfield
Review of Arrays and Pointers
Introduction To Programming Information Technology , 1’st Semester
Arrays .
24 Searching and Sorting.
Data Structures (CS212D) Week # 2: Arrays.
Chapter 8 Spring 2006 CS 101 Aaron Bloomfield
Arrays Week 2.
COMS 261 Computer Science I
Chapter 6 Arrays.
7 Arrays.
Arrays in Java.
Chapter 6 Arrays.
Suggested self-checks: Section 7.11 #1-11
Chapter 8 Multidimensional Arrays
Consider Write a program that prompts a user to enter the number of students and then, their names and grades. The program will then outputs the average.
COMS 261 Computer Science I
Sorting.
How do you do the following?
Review for Midterm 3.
Arrays.
A type is a collection of values
Algorithms and data structures: basic definitions
Presentation transcript:

Arrays

Background Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional Java provides arrays and the collection classes Consider arrays first

Basic terminology List is composed of elements Elements in a list have a common name The list as a whole is referenced through the common name List elements are of the same type — the base type Elements of a list are referenced by subscripting (indexing) the common name

Java array features Subscripts are denoted as expressions within brackets: [ ] Base (element) type can be any type Size of array can be specified at run time Index type is integer and the index range must be 0 ... n-1 Where n is the number of elements Automatic bounds checking Ensures any reference to an array element is valid Data field length specifies the number of elements in the list Array is an object Has features common to all other objects More robust than arrays in most programming languages

Array variable definition styles Without initialization

Array variable definition styles With initialization

Example Definitions char[] c; int[] value = new int[10]; Causes Array object variable c is un-initialized Array object variable v references a new ten element list of integers Each of the integers is default initialized to 0 c can only reference char arrays v can only reference int arrays

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); 8 is displayed int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider int[] v = new int[10]; int i = 7; int j = 2; int k = 4; v[i] = 5; v[j] = v[i] + 3; v[j+1] = v[i] + v[0]; v[v[j]] = 12; System.out.println(v[2]); v[k] = Integer.parseInt(stdin.readLine()); Suppose 3 is extracted int i = 7; int j = 2; int k = 4; v[0] = 1; // element 0 of v given value 1 v[i] = 5; // element i of v given value 5 v[j] = v[i] + 3; // element j of v given value // of element i of v plus 3 v[j+1] = v[i] + v[0]; // element j+1 of v given value // of element i of v plus // value of element 0 of v v[v[j]] = 12; // element v[j] of v given // value 12 System.out.println(v[2]); // element 2 of v is displayed v[k] = Integer.parseInt(stdin.readLine()); // element k of v given next // extracted value

Consider Segment int[] b = new int[100]; b[-1] = 0; b[100] = 0; Causes Array variable to reference a new list of 100 integers Each element is initialized to 0 Two exceptions to be thrown -1 is not a valid index – too small 100 is not a valid index – too large IndexOutOfBoundsException int[] b = new int[100]; // b has 100 elements: b[0], … b[99] b[-1] = 0; // illegal: subscript too small b[100] = 0; // illegal: subscript too large

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Consider Point[] p = new Point[3]; p[0] = new Point(0, 0); p[0].setX(1); p[1].setY(p[2].getY()); Point vertex = new Point(4,4); p[1] = p[0]; p[2] = vertex;

Explicit initialization Syntax

Explicit initialization Example String[] puppy = { "nilla“, “darby“, "galen", "panther" }; int[] unit = { 1 }; Equivalent to String[] puppy = new String[4]; puppy[0] = "nilla"; puppy[1] = “darby"; puppy[2] = "galen"; puppy[4] = "panther"; int[] unit = new int[1]; unit[0] = 1;

Array members Member length Size of the array for (int i = 0; i < puppy.length; ++i) { System.out.println(puppy[i]); }

Array members Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30);

Array members Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30);

Array members Member clone() Produces a shallow copy Point[] u = { new Point(0, 0), new Point(1, 1)}; Point[] v = u.clone(); v[1] = new Point(4, 30);

Making a deep copy Example Point[] w = new Point[u.length]; for (int i = 0; i < u.length; ++i) { w[i] = u[i].clone(); }

Making a deep copy

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + I + "-th element"); else { System.out.println(key + " is not in the list");

Searching for a value System.out.println("Enter search value (number): "); int key = Integer.parseInt(stdin.readLine()); int i; for (i = 0; i < data.length; ++i) { if (key == data[i]) { break; } if (i != data.length) { System.out.println(key + " is the " + i + "-th element"); else { System.out.println(key + " is not in the list");

Searching for the minimum value Segment int minimumSoFar = sample[0]; for (int i = 1; i < sample.length; ++i) { if (sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } The key value search code segment is typical of array processing. There is initialization to prepare for the processing of the array, a loop to process each array element in turn, and a check to see how the list processing completed. For example, the next code segment finds the minimum value of a list sample where the list size of sample is at least 1. int minimumSoFar = sample[0]; for (int i = 1; i < sample.length; ++i) { if (sample[i] < minimumSoFar) { minimumSoFar = sample[i]; } To find the minimum value in an array requires examining each element in turn. If the code segment keeps track of the minimum array element value seen so far, the lesser of that value and the current element is the minimum value seen so far. If this processing is done for each array element, then after the last array element has been considered, the minimum value seen so far is in fact the minimum. Observe that our code segment for finding the minimum of an arbitrarily sized list is even smaller than the code segment presented at the start of this chapter for finding the minimum of five values!

ArrayTools.java method sequentialSearch() public static int sequentialSearch(int[] data, int key) { for (int i = 0; i < data.length; ++i) { if (data[i] == key) { return i; } return -1; Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; int i1 = sequentialSearch(score, 11); int i2 = sequentialSearch(score, 30); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.

ArrayTools.java method sequentialSearch() public static int sequentialSearch(int[] data, int key) { for (int i = 0; i < data.length; ++i) { if (data[i] == key) { return i; } return -1; Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; int i1 = sequentialSearch(score, 11); int i2 = sequentialSearch(score, 30); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.

ArrayTools.java method putList() public static void putList(int[] data) { for (int i = 0; i < data.length; ++i) { System.out.println(data[i]); } Consider int[] score = { 6, 9, 82, 11, 29, 85, 11, 28, 91 }; putList(score); Method sequentialSearch() has two formal parameters—the first parameter is an int[] array data and the second parameter is the search value key. Method sequentialSearch() is similar in form to the code segment that searched an array for a key value in Section . However, sequentialSearch() does not display a message indicating whether it found the value. If sequentialSearch() finds the key value in the array, it returns the subscript of the first matching element. If the key value is not among the array element values, sequentialSearch() returns the number of elements in the array. Because the array elements occupy subscript positions 0 through data.length-1 in the array, the value -1 indicates that the key value is not in the array.

ArrayTools.java method getList() public static int[] getList() throws IOException { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); int[] buffer = new int[MAX_LIST_SIZE]; int listSize = 0; for (int i = 0; i < MAX_LIST_SIZE; ++i) { String v = stdin.readLine(); if (v != null) { int number = Integer.parseInt(v); buffer[i] = number; ++listSize; } else { break; int[] data = new int[listSize]; for (int i = 0; i < listSize; ++i) { data[i] = buffer[i]; return data; ArrayTools.java method getList()

ArrayTools.java – outline public class ArrayTools { // class constant private static final int MAX_LIST_SIZE = 1000; // sequentialSearch(): examine unsorted list for key public static int binarySearch(int[] data, int key) { ... // valueOf(): produces a string representation public static void putList(int[] data) { ... // getList(): extract and return up to MAX_LIST_SIZE values public static int[] getList() throws IOException { ... // reverse(): reverses the order of the element values public static void reverse(int[] list) { ... // binarySearch(): examine sorted list for a key public static int binarySearch(char[] data, char key) { ... }

Demo.java import java.io.*; public class Demo { // main(): application entry point public static void main(String[] args) throws IOException { System.out.println(""); System.out.println("Enter list of integers:"); int[] number = ArrayTools.getList(); System.out.println("Your list"); ArrayTools.putList(number); ArrayTools.reverse(number); System.out.println("Your list in reverse"); System.out.println(); }

Sorting Problem Arranging elements so that they are ordered according to some desired scheme Standard is non-decreasing order Why don't we say increasing order? Major tasks Comparisons of elements Updates or element movement Chapter introduced the notion of sorting in SortTwo.java and SortThree.java, which respectively displayed two and three input values in nondecreasing order. We used the term nondecreasing rather than increasing to allow for duplicate values. Here we consider the general sorting problem of arranging the values in a list of arbitrary size into nondecreasing order. A sort is often an iterative process such that each iteration rearranges some of the values in the list v to be sorted. For example, on iteration i the method known as selectionSort() finds the element containing the ith smallest value of its list v and exchanges that element with v[i]. As another example, on iteration i the method known as insertionSort() correctly places the value of v[i] with respect to the values stored in elements v[0] through v[i-1].

Selection sorting Algorithm basis On iteration i, a selection sorting method Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place for a sorted result

Selection sorting Algorithm basis On iteration i, a selection sorting method Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 0 Swaps smallest element with v[0] This results in smallest element being in the correct place for a sorted result

Selection sorting Algorithm basis On iteration i, a selection sorting method Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the correct place for a sorted result

Selection sorting Algorithm basis On iteration i, a selection sorting method Finds the element containing the ith smallest value of its list v and exchanges that element with v[i] Example – iteration 1 Swaps second smallest element with v[1] This results in second smallest element being in the correct place for a sorted result

ArrayTools.java selection sorting public static void selectionSort(char[] v) { for (int i = 0; i < v.length-1; ++i) { // guess the location of the ith smallest element int guess = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[guess]) { // is guess ok? // update guess to index of smaller element guess = j; } // guess is now correct, so swap elements char rmbr = v[i]; v[i] = v[guess]; v[guess] = rmbr; In analyzing a sorting algorithm, software developers are concerned normally with the total number of element comparisons and the total number of element copies/assignments performed by the sort. When i is 0 for selectionSort(), there are n – 1 element comparisons and 3 element copies/assignments, where n is the number of elements in array v. When i is 1, there are n – 2 element comparisons and 3 element copies/assignments. When i is 2, there are n – 3 element comparisons and 3 element copies/assignments. In general, on iteration i, there are n – (i + 1) element comparisons and 3 element copies/ assignments. The total number of element comparisons is therefore n – 1 + n – 2 + … + 2 + 1, which is proportional to n2. The total number of element copies/assignments is at most 3 + 3 + … + 3, which is proportional to n. Because the number of element comparisons is proportional to the square of the number of elements, we say that method selectionSort() has quadratic performance with respect to element comparisons. Because the number of element copies/assignments is proportional to the number of elements, we say that the algorithm has linear performance with respect to element copies/assignments. Because n2 > n, we say that overall algorithm performs a quadratic number of element operations.

Iteration i // guess the location of the ith smallest element int guess = i; for (int j = i+1; j < v.length; ++j) { if (v[j] < v[guess]) // is guess ok? // update guess with index of smaller element guess = j; } // guess is now correct, swap elements v[guess] and v[0] The code is similar to our other array processing code. In particular, the code is most similar to the code that searches an array. The code segment begins defining int index variable guess. Variable guess represents where we believe the ith smallest element can be found. The definition initializes guess to i. The code segment then determines whether the value of guess is correct. The for loop body repeatedly tests whether v[j] < v[guess], with j iteratively taking on the values i + 1 through v.length - 1. If it is determined that v[j] < v[guess], then our value for guess is wrong and it is updated with the value of j. At this point, guess is the index of the smallest value among elements v[i] through v[j]. Thus, completing the for loop assures that guess is the index of the ith smallest element.

Multidimensional arrays Many problems require information be organized as a two-dimensional or multidimensional list Examples Matrices Graphical animation Economic forecast models Map representation Time studies of population change Microprocessor design In addition to defining one-dimensional arrays, it is also possible to define multidimensional arrays. There are a great many problems whose solutions can be determined through the manipulation of multidimensional arrays. The application domains include matrices, graphical animation, economic forecast models, map representation, time studies of population change, and microprocessor design to name just a few.

Example Segment int[][] m = new int[3][]; m[0] = new int[4]; Produces

Example Segment for (int r = 0; r < m.length; ++r) { for (int c = 0; c < m[r].length; ++c) { System.out.print("Enter a value: "); m[r][c] = Integer.parseInt(stdin.readLine()); }

Example Segment String[][] s = new String[4][]; s[0] = new String[2]; Produces

Example Segment int c[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8, 9}}; Produces

Matrices A two-dimensional array is sometimes known as a matrix because it resembles that mathematical concept A matrix a with m rows and n columns is represented mathematically in the following manner

Matrix addition cij = a1ib1j + ai2b2j + . . . + ainbnj Definition C = A + B cij = a1ib1j + ai2b2j + . . . + ainbnj cij is sum of terms produced by multipling the elements of a’s row i with b’s column c

Matrix addition public static double[][] add(double[][] a, double[][] b) { // determine number of rows in solution int m = a.length; // determine number of columns in solution int n = a[0].length; // create the array to hold the sum double[][] c = new double[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; ++i) { // produce the current row for (int j = 0; j < n; ++j) { c[i][j] = a[i][j] + b[i][j]; } return c;