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

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

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 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

CS1150 Principles of Computer Science Arrays

CS115 Principles of Computer Science

Chapter 7 Single-Dimensional Arrays

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

Module 7: Arrays (Single Dimensional)

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

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

Lecture #8-10 Arrays

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

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

CS1150 Principles of Computer Science Arrays

16. Searching and Sorting

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

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

OOP Part 2. Introduction to OOP with Java. Lecture 08: Introduction to OOP with Java - AKF Sep AbuKhleiF -

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

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Arrays. Eng. Mohammed Abdualal

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Lecture 7: Searching and Sorting Algorithms

array Indexed same type

Chapter 8 Multi-Dimensional Arrays

Chapter 7 Multidimensional Arrays

Introduction. Introduction to OOP with Java. Lecture 01: Introduction to OOP with Java - AKF Sep AbuKhleiF -

Chapter 6 Single-dimensional Arrays

Data Types. Operators, Assignment, Output and Return Statements

LAB 13: ARRAYS (ONE DIMINSION)

Chapter 8 Multidimensional Arrays

Passing Array to Methods

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

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

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

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

Introduction. Data in a table or a matrix can be represented using a two-dimensional array. For example:

Objectives. Chapter 23 Sorting. Why study sorting? What data to sort? Insertion Sort. CS1: Java Programming Colorado State University

Spring 2010 Java Programming

Objectives of the lesson

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

ARRAYS and ARRAYLISTS

15. Multidimensional Arrays

Computer Science is...

Problems with simple variables

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

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

C/C++ Programming Lecture 18 Name:

Arrays. Week 4. Assylbek Jumagaliyev

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

Introduction to Programming Using Java (98-388)

Chapter 10 - Notes Applications of Arrays

Introduction to Java & Fundamental Data Types

Chapter 6. Arrays. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

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

Advanced Computer Programming

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

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

About this exam review

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

Chapter 6: Using Arrays

Lecture 6 Sorting and Searching

Arrays. Chapter 6. Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Multidimensional Arrays

Top-down programming design

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

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

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

BM214E Object Oriented Programming Lecture 4

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

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

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Pace University. Fundamental Concepts of CS121 1

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

Arrays and Applications

Introduction to Computer Science Midterm 3 Fall, Points

Computer Science II Data Structures

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

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

CS 106 Introduction to Computer Science I

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

CS101 Part 2: Practice Questions Algorithms on Arrays, Classes and Objects, String Class, Stack Class

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

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

Arrays & Linked Lists

Chapter 9 Introduction to Arrays. Fundamentals of Java

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Data Structures and Algorithms for Engineers

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

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

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

Transcription:

Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 06: Arrays Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1

Instructor AbuKhleif, Mohammad Noor Computer Engineer (JU 2012-2017) Software Automation Engineer @ Atypon John Wiley and Sons Company - Jordan Branch Reach me at: moh.noor94@gmail.com facebook.com/moh.noor94 twitter.com/moh_noor94 3 Course Java SE Basics Object Oriented Programming Course Page: /courses/java-101-sep-2017 Or, go to: Courses Java 101 Course Sep 2017 Course Facebook Group: www.facebook.com/groups/akf2017java 4 AbuKhleiF - 2

Let s Start! 5 Opening Problem Read one hundred marks, compute their average, and find out how many numbers are above the average. 6 AbuKhleiF - 3

Introducing Arrays 7 Introducing Arrays Array is a data structure that represents a collection of the same types of data. double[] mylist = new double[10]; mylist reference mylist[0] mylist[1] 5.6 4.5 Array reference variable mylist[2] mylist[3] 3.3 13.2 Array element at index 5 mylist[4] mylist[5] mylist[6] mylist[7] mylist[8] mylist[9] 4 34.33 34 45.45 99.993 11123 Element value 8 AbuKhleiF - 4

Declaring Arrays To use an array in a program, you must declare a variable to reference the array and specify the array s elements type. All elements in the array have the same data type. The syntax for declaring an array variable is: datatype[] arrayrefvar; Example: double[] mylist; datatype arrayrefvar[]; // This style is allowed, but not preferred Example: double mylist[]; 9 Declaring Arrays, cont. Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. 10 AbuKhleiF - 5

Creating Arrays An array is created using the new operator with the following syntax: arrayrefvar = new elementtype [arraysize]; This statement does two things: It creates an array using new elementtype [arraysize]; It assigns the reference of the newly created array to the variable arrayrefvar. Example: double [] mylist; /array declaration mylist = new double [10]; /array creation 11 Creating Arrays, cont. Array declaration and creation can be combined in one statement: elementtype [] arrayrefvar = new elementtype [arraysize]; Example: double [] mylist = new double [10]; 12 AbuKhleiF - 6

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 For example: mylist.length returns 10 13 Default Values When an array is created, its elements are assigned the default value of : 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types. 14 AbuKhleiF - 7

Indexed Variables The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayrefvar.length-1. In the example in Slide 8, mylist holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayrefvar[index]; 15 Using Indexed Variables After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in mylist[0] and mylist[1] to mylist[2]. mylist[2] = mylist[0] + mylist[1]; 16 AbuKhleiF - 8

Array Initializers Declaring, creating, initializing in one step: double[] mylist = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement. 17 Declaring, creating, initializing Using the Shorthand Notation double[] mylist = {1.9, 2.9, 3.4, 3.5}; 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; 18 AbuKhleiF - 9

Caution Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] mylist; mylist = {1.9, 2.9, 3.4, 3.5}; 19 Processing Arrays When processing array elements, you will often use a for loop. All elements in an array are of the same type and they are evenly processed in the same fashion repeatedly using a loop. Since the size of the array is known, it is natural to use a for loop. For example, to print an array, you have to print each element in the array using a loop like the following: for (int i = 0; i < mylist.length; i++) System.out.print (mylist[i] + ); 20 AbuKhleiF - 10

Example 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 Final Contents 0 11 1 1 2 3 3 6 4 10 21 Let s Code Solve the Opening Problem of this chapter. 22 AbuKhleiF - 11

Enhanced for Loop (for-each Loop) 23 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: for (double 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. 24 AbuKhleiF - 12

Let s Code Resolve the Opening Problem of this chapter using the enhanced for loop. 25 Copying Arrays 26 AbuKhleiF - 13

Copying Arrays The assignment operator does not copy the contents of an array into another, it instead merely copies the reference values. Before the assignment list2 = list1; After the assignment list2 = list1; list1 Contents of list1 list1 Contents of list1 list2 Contents of list2 list2 Garbage Contents of list2 27 Copying Arrays, cont. To copy the contents of one array into another, you have to copy the array s individual elements into the other array. Use a loop to copy every element from the source array to the corresponding element in the target array. Example: int [] sourcearray = {2, 3, 1, 5, 10}; int [] targetarray = new int [sourcearray.length]; for (int i=0; i < sourcearray.length; i++) targetarray [i] = sourcearray [i]; 28 AbuKhleiF - 14

Copying Arrays, cont. (The arraycopy Utility) arraycopy(sourcearray, src_pos, targetarray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetarray, 0, sourcearray.length); 29 Passing Arrays to Methods 30 AbuKhleiF - 15

Passing Arrays to Methods 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. 31 public class Test { public static void main(string[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y represents an array of int values m(x, y); // Invoke m with arguments x and y } System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); Example public static void m(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] } } 32 AbuKhleiF - 16

When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array. Example, cont. 33 Passing Arrays to Methods, cont. Please study the following example: http://www.cs.armstrong.edu/liang/intro9e/html/testpassarray.html Objective: Demonstrate differences of passing primitive data type variables and array variables. 34 AbuKhleiF - 17

Anonymous Array The statement printarray(new int[]{3, 1, 2, 6, 4, 2}); creates an array using the following syntax: new datatype[]{literal0, literal1,..., literalk}; There is no explicit reference variable for the array. Such array is called an anonymous array. 35 Returning an Array from a Method 36 AbuKhleiF - 18

Returning an Array from a Method When a method returns an array, the reference of the array is returned. Example: public static int[] copy(int [] list) { int [] result = new int [list.length]; } for (int i=0; i < list.length; i++) result[i]=list[i]; return result; Example of this method invocation: int [] list1 = {1, 2, 3, 4, 5}; int [] list2 = copy(list1); 37 Searching Arrays 38 AbuKhleiF - 19

Searching Arrays Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search. 39 Linear Search The linear search approach compares the key element, key, 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. 40 AbuKhleiF - 20

Key List Linear Search, cont. 3 3 3 3 3 3 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 41 Linear Search, cont. Try different examples by animation here: http://www.cs.armstrong.edu/liang/animation/web/linearse arch.html 42 AbuKhleiF - 21

Linear Search, From Idea to Solution /** 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]) return i; return -1; } Trace the method: int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearsearch(list, 4); // returns 1 int j = linearsearch(list, -4); // returns -1 int k = linearsearch(list, -3); // returns 5 43 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. 44 AbuKhleiF - 22

Binary Search, cont. Consider the following three cases: 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. 45 Binary Search, cont. Key List 8 8 8 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 46 AbuKhleiF - 23

Binary Search, cont. Try this example with animation: http://www.cs.armstrong.edu/liang/animation/web/binaryse arch.html 47 key is 11 low mid high key < 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] list 2 4 7 10 11 45 50 59 60 66 69 70 79 key > 7 list low mid high [0] [1] [2] [3] [4] [5] 2 4 7 10 11 45 Example 1 low mid high key == 11 list [3] [4] [5] 10 11 45 48 AbuKhleiF - 24

key is 54 low mid high key > 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] list 2 4 7 10 11 45 50 59 60 66 69 70 79 low mid high key < 66 list [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] 59 60 66 69 70 79 low mid high Example 2 key < 59 list [7] [8] 59 60 low high [6] [7] [8] 59 60 49 Binary Search, cont. The binarysearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -1 50 AbuKhleiF - 25

Binary Search, From Idea to 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; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } } return -1 - low; 51 The Arrays.binarySearch Method 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, the following code searches the keys in an array of numbers and an array of characters. int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println("Index is " + java.util.arrays.binarysearch(list, 11)); char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'}; System.out.println("Index is " + java.util.arrays.binarysearch(chars, 't')); For the binarysearch method to work, the array must be pre-sorted in increasing order. 52 AbuKhleiF - 26

Let s Code Revisit your Opening Problem solution, edit it by letting the user enter the mark and the name for each student. Then let the user enter any mark and return the name of first student with such a mark. If the mark does not found, print appropriate message clarifying that. 53 Sorting Arrays 54 AbuKhleiF - 27

Sorting Arrays Sorting, like searching, is also a common task in computer programming. Many different algorithms have been developed for sorting. This section introduces two simple, intuitive sorting algorithms: selection sort and insertion sort. 55 Selection Sort swap Select 1 (the smallest) and swap it with 2 (the first) in the list Select 2 (the smallest) and swap it with 9 (the first) in the remaining list Select 4 (the smallest) and swap it with 5 (the first) in the remaining list 5 is the smallest and in the right position. No swap is necessary Select 6 (the smallest) and swap it with 8 (the first) in the remaining list Select 8 (the smallest) and swap it with 9 (the first) in the remaining list Since there is only one element remaining in the list, sort is completed 2 9 5 4 8 1 6 swap 1 9 5 4 8 2 6 swap 1 2 5 4 8 9 6 1 2 4 5 8 9 6 swap 1 2 4 5 8 9 6 swap 1 2 4 5 6 9 8 1 2 4 5 6 8 9 The number 1 is now in the correct position and thus no longer needs to be considered. The number 2 is now in the correct position and thus no longer needs to be considered. The number 6 is now in the correct position and thus no longer needs to be considered. The number 5 is now in the correct position and thus no longer needs to be considered. The number 6 is now in the correct position and thus no longer needs to be considered. The number 8 is now in the correct position and thus no longer needs to be considered. 56 AbuKhleiF - 28

Selection Sort, cont. Try this example with animation: http://www.cs.armstrong.edu/liang/animation/web/selection Sort.html 57 Selection Sort From Idea to Solution for (int i = 0; i < list.length; i++) { / 1. select the smallest element in list[i..listsize-1]; / 2. swap the smallest with list[i], if necessary; / list[i] is in its correct position. / The next iteration apply on list[i..listsize-1] } 58 AbuKhleiF - 29

/** 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; } Selection Sort Code 59 Insertion Sort The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. 60 AbuKhleiF - 30

Insertion Sort Example int[] mylist = {2, 9, 5, 4, 8, 1, 6}; / Unsorted 2 9 5 4 8 1 6 2 5 9 4 8 1 6 2 4 5 8 9 1 6 1 2 4 5 6 8 9 2 9 5 4 8 1 6 2 4 5 9 8 1 6 1 2 4 5 8 9 6 61 Insertion Sort Example, More Details int[] mylist = {2, 9, 5, 4, 8, 1, 6}; / Unsorted Step 1: Initially, the sorted sublist contains the first element in the list. Insert 9 into the sublist. 2 9 5 4 8 1 6 Step2: The sorted sublist is {2, 9}. Insert 5 into the sublist. 2 9 5 4 8 1 6 Step 3: The sorted sublist is {2, 5, 9}. Insert 4 into the sublist. 2 5 9 4 8 1 6 Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 into the sublist. 2 4 5 9 8 1 6 Step 5: The sorted sublist is {2, 4, 5, 8, 9}. Insert 1 into the sublist. 2 4 5 8 9 1 6 Step 6: The sorted sublist is {1, 2, 4, 5, 8, 9}. Insert 6 into the sublist. 1 2 4 5 8 9 6 Step 7: The entire list is now sorted. 1 2 4 5 6 8 9 62 AbuKhleiF - 31

Insertion Sort, cont. Try this example with animation: http://www.cs.armstrong.edu/liang/animation/web/insertion Sort.html 63 Insertion Sort How to Insert? The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted. list list list list [0] [1] [2] [3] [4] [5] [6] 2 5 9 4 [0] [1] [2] [3] [4] [5] [6] 2 5 9 [0] [1] [2] [3] [4] [5] [6] 2 5 9 [0] [1] [2] [3] [4] [5] [6] 2 4 5 9 Step 1: Save 4 to a temporary variable currentelement Step 2: Move list[2] to list[3] Step 3: Move list[1] to list[2] Step 4: Assign currentelement to list[1] 64 AbuKhleiF - 32

Insertion Sort From Idea to Solution for (int i = 1; i < list.length; i++) { / insert list[i] into a sorted sublist list[0..i-1] so that / list[0..i] is sorted } 65 Insertion Sort From Idea to Solution Insertion sort solution can be found here: http://www.geeksforgeeks.org/insertion-sort/ 66 AbuKhleiF - 33

Insertion Sort The 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. 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); 67 Let s Code Revisit your Opening Problem solution, sort the marks of all students and print the results. 68 AbuKhleiF - 34

Introduction to Multi-Dimensional Arrays 69 Two-Dimensional Arrays Two dimensional arrays are used to represent data in a matrix or a table. The syntax for declaring and creating two dimensional arrays is: elementtype [] [] arrayrefvar; arrayrefvar = new elementtype [numrows][numcols]; An element in a two-dimensional array is accessed through a row and column index: arrayrefvar [rowindex][colindex]; 70 AbuKhleiF - 35

Two-Dimensional Arrays, cont. A two-dimensional array is actually an array in which each element is a one-dimensional array. x x[0] x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4 x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4 x[2] x.length is 3 x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4 71 Two-Dimensional Arrays Examples [0] [1] [2] [3] [4] 4 [0] 0 0 0 0 0 [1] 0 0 0 0 0 [2] 0 0 0 0 0 [3] 0 0 0 0 0 [4] 0 0 0 0 0 matrix = new int[5][5]; matrix.length? 5 matrix[0].length? 5 [0] [1] [2] [3] [4] [0] 4 0 0 0 0 0 [1] 0 0 0 0 0 [2] [3] [4] 0 7 0 0 0 0 0 0 0 0 0 0 0 0 0 matrix[2][1] = 7; array.length? 4 array[0].length? 3 [0] [1] [2] [3] [0] [1] [2] [3] 1 2 3 4 5 6 7 8 9 10 11 12 [4] int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; 72 AbuKhleiF - 36

Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] trianglearray = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5 73 Processing Two-Dimensional Arrays When processing two-dimensional array elements, you will often use a nested for loop. All elements in an array are of the same type and they are evenly processed in the same fashion repeatedly using a loop. Since the size of the array is known, it is natural to use a for loop. For example, to print a two-dimensional array, you have to print each element in the array using a loop like the following: for (int i = 0; i < mylist.length; i++) for (int j = 0; j < mylist[i].length; j++) System.out.print (mylist[i][j] + ); 74 AbuKhleiF - 37

Processing Two-Dimensional Arrays Example Study and execute the following example in your machine: http://www.cs.armstrong.edu/liang/intro9e/html/passtwodi mensionalarray.html 75 Multidimensional Arrays Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n-dimensional arrays for n >= 3. 76 AbuKhleiF - 38

Multidimensional Arrays - Example double[][][] scores = { {{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}}, {{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}}, {{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}}, {{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}}, {{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}}, {{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}}; Which student Which exam Multiple-choice or essay scores[ i ] [ j ] [ k ] 77 Tasks All tasks should be well-documented, well-designed, and well-styled. AbuKhleiF - 39

Task 01 (Reverse the numbers entered) Write a program that reads ten integers and displays them in the reverse of the order in which they were read. 79 Task 02 (Average an array) Write two overloaded methods that return the average of an array with the following headers: public static int average(int[] array) public static double average(double[] array) Write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value. 80 AbuKhleiF - 40

Task 03 (Eliminate duplicates) Write a method that returns a new array by eliminating the duplicate values in the array using the following method header: public static int[] eliminateduplicates(int[] list) Write a test program that reads in ten integers, invokes the method, and displays the result. Here is the sample run of the program: Enter ten numbers: 1 2 3 2 1 6 3 4 5 2 The distinct numbers are: 1 2 3 6 4 5 81 Task 04 (Optional) (Sorted?) ** Write the following method that returns true if the list is already sorted in increasing order. public static boolean issorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. This number is not part of the list. Next slide shows sample runs. 82 AbuKhleiF - 41

Task 04 (Optional) Sample Runs Enter list: 8 10 1 5 16 61 9 11 1 The list is not sorted Enter list: 10 1 1 3 4 4 5 7 9 11 21 The list is already sorted 83 Task 05 (Optional) (Locate the largest element) * Write the following method that returns the location of the largest element in a two-dimensional array. public static int[] locatelargest(double[][] a) The return value is a one-dimensional array that contains two elements. These two elements indicate the row and column indices of the largest element in the two-dimensional array. Write a test program that prompts the user to enter a two-dimensional array and displays the location of the largest element in the array. Next slide shows a sample run. 84 AbuKhleiF - 42

Task 05 (Optional) Sample Run Enter the number of rows and columns of the array: 3 4 Enter the array: 10 2 35 23.5 3.5 45 3 4.5 9.6 5.5 44 35 The location of the largest element is at (1, 2) 85 Tasks Submission Submit a zipped file contains all the.java files, 1 file for each task. Name your zipped file as follow [Lect6_YourName.zip]. Upload your zipped file to the Facebook group. Submission due: Thursday, Sep 21-10:00 PM Late submission will not be reviewed by the instructor. Public solutions upload goal is to share knowledge, you can see other s solutions, but, please, don t cheat yourself! Don t forget, all tasks should be well-documented, well-designed, and well-styled. 86 AbuKhleiF - 43

Test Yourself Answer all question: http://www.cs.armstrong.edu/liang/interactivequiz/pu blic_html/chapter7.html And http://www.cs.armstrong.edu/liang/interactivequiz/pu blic_html/chapter8.html 87 References: - Liang, Introduction to Java Programming 10/e - Eng. Asma Abdel Karim Computer Engineering Department, JU Slides. Instructor: AbuKhleif, Mohammad Noor Sep 2017 End of Lecture =D AbuKhleiF - 44