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

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.

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

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

Chapter 7 Single-Dimensional Arrays

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

CS1150 Principles of Computer Science Arrays

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

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)

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

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

16. Searching and Sorting

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Lecture #8-10 Arrays

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

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

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

Objectives of the lesson

Chapter 6 Single-dimensional Arrays

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

Data Types. Operators, Assignment, Output and Return Statements

Arrays. Eng. Mohammed Abdualal

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

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

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

Lecture 7: Searching and Sorting Algorithms

array Indexed same type

Lecture 6 Sorting and Searching

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

Chapter 10 - Notes Applications of Arrays

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

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

Chapter 7 Arrays and Vectors

Declaring Array Variable

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

CSE 143 Lecture 4. Implementing ArrayIntList; Binary Search. reading:

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

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

Example. Password generator

Chapter 8 Multidimensional Arrays

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

LAB 13: ARRAYS (ONE DIMINSION)

CS 106 Introduction to Computer Science I

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

CS 103 Lecture 4 Slides

CSCI 136 Data Structures & Advanced Programming. Lecture 12 Fall 2018 Profs Bill & Jon

About this exam review

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

Introduction to Java & Fundamental Data Types

Sorting and searching arrays

SCALA ARRAYS. Following picture represents array mylist. Here, mylist holds ten double values and the indices are from 0 to 9.

Chapter 18 Recursion. Motivations

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

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:

3/20/2015. Chapter 19 Sorting and Searching SELECTION SORT INSERTION SORT MERGE SORT THE QUICKSORT ALGORITHM MERGE SORT VS SELECTION SORT

Advanced Computer Programming

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Data Structures and Algorithms for Engineers

Binary Search. Roland Backhouse February 5th, 2001

Searching & Sorting in Java Bubble Sort

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

Chapter 8 Multi-Dimensional Arrays

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Problems with simple variables

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning

Spring 2010 Java Programming

Chapter 8 Algorithms 1

Introduction to Programming Using Java (98-388)

Java Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari

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

CS1150 Principles of Computer Science Loops (Part II)

Algorithm must complete after a finite number of instructions have been executed. Each step must be clearly defined, having only one interpretation.

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Computer programming Code exercises [1D Array]

Arrays in Java Using Arrays

Arrays & Linked Lists

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Searching. 11. Searching

Here we will only consider the problem of searching among the elements of an array. Intro Programming in C++

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

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

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

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

Java Coding 3. Over & over again!

C/C++ Programming Lecture 18 Name:

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L

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

Tail Recursion: working from the beginning towards the end.

CEN 414 Java Programming

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS/CE 2336 Computer Science II

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Transcription:

Chapter 7: Single-Dimensional Arrays Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox rights reserved 1 rights reserved 2 Introducing Arrays Array is a data structure that represents a collection of the same types of data Declaring Array Variables datatype[] arrayrefvar; Example: double[] mylist; datatype arrayrefvar[]; // This style is allowed, but not preferred Example: double mylist[]; rights reserved rights reserved 4 Creating Arrays arrayrefvar = new datatype[arraysize]; Example: mylist = new double[1]; mylist[] references the first element in the array mylist[9] references the last element in the array Declaring and Creating in One Step datatype[] arrayrefvar = new datatype[arraysize]; double[] mylist = new double[1]; datatype arrayrefvar[] = new datatype[arraysize]; double mylist[] = new double[1]; rights reserved 5 rights reserved 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 arrayrefvarlength For example, Default Values When an array is created, its elements are assigned the default value of for the numeric primitive data types, '\u' for char types, and for boolean types mylistlength returns 1 rights reserved 7 rights reserved 8 Indexed Variables The array elements are accessed through the index The array indices are -based, ie, it starts from to arrayrefvarlength-1 In the example in Figure 61, mylist holds ten double values and the indices are from to 9 Each element in the array is represented using the following syntax, known as an indexed variable: 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[] and mylist[1] to mylist[2] mylist[2] = mylist[] + mylist[1]; arrayrefvar[index]; rights reserved 9 rights reserved 1 Array Initializers Declaring, creating, initializing in one step: double[] mylist = {19, 29, 4, 5; This shorthand syntax must be in one statement Declaring, creating, initializing Using the Shorthand Notation double[] mylist = {19, 29, 4, 5; This shorthand notation is equivalent to the following statements: double[] mylist = new double[4]; mylist[] = 19; mylist[1] = 29; mylist[2] = 4; mylist[] = 5; rights reserved 11 rights reserved 12

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; Declare array variable values, create an array, and assign its reference to values After the array is created 1 2 4 mylist = {19, 29, 4, 5; rights reserved 1 rights reserved 14 i becomes 1 i (=1) is less than 5 After the array is created 1 2 After the array is created 1 2 rights reserved 15 rights reserved 16 After this line is executed, value[1] is 1 After i++, i becomes 2 After the first iteration 2 After the first iteration 2 rights reserved 17 rights reserved 18

public static void main(string[] args) { values[] = values[1] + values[4]; i (= 2) is less than 5 After the first iteration 2 After this line is executed, values[2] is (2 + 1) After the second iteration rights reserved 19 rights reserved 2 After this, i becomes i (=) is still less than 5 After the second iteration After the second iteration rights reserved 21 rights reserved 22 After this line, values[] becomes 6 ( + ) After this, i becomes 4 After the third iteration 6 After the third iteration 6 rights reserved 2 rights reserved 24

i (=4) is still less than 5 After this, values[4] becomes 1 (4 + 6) After the third iteration 6 After the fourth iteration 6 4 1 rights reserved 25 rights reserved 26 After i++, i becomes 5 i ( =5) < 5 is Exit the loop After the fourth iteration 6 4 1 After the fourth iteration 6 4 1 rights reserved 27 rights reserved 28 After this line, values[] is 11 (1 + 1) Initializing arrays with input values 1 2 4 11 1 6 1 javautilscanner input = new javautilscanner(systemin); Systemoutprint("Enter " + mylistlength + " values: "); for (int i = ; i < mylistlength; i++) mylist[i] = inputnextdouble(); rights reserved 29 rights reserved

Initializing arrays with random values for (int i = ; i < mylistlength; i++) { mylist[i] = Mathrandom() * 1; Printing arrays for (int i = ; i < mylistlength; i++) { Systemoutprint(myList[i] + " "); rights reserved 1 rights reserved 2 Summing all elements double total = ; for (int i = ; i < mylistlength; i++) { total += mylist[i]; Finding the largest element double max = mylist[]; for (int i = 1; i < mylistlength; i++) { if (mylist[i] > max) max = mylist[i]; rights reserved rights reserved 4 Shifting Elements Enhanced for Loop (for-each loop) JDK 15 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) Systemoutprintln(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 rights reserved 5 rights reserved 6

Analyze Numbers Read one hundred numbers, compute their average, and find out how many numbers are above the average Problem: Deck of Cards The problem is to write a program that picks four cards randomly from a deck of 52 cards All the cards can be represented using an array named deck, filled with initial values to 51, as follows: int[] deck = new int[52]; // Initialize cards for (int i = ; i < decklength; i++) deck[i] = i; AnalyzeNumbers Run DeckOfCards Run rights reserved 7 rights reserved 8 Problem: Deck of Cards, cont Problem: Deck of Cards, cont GUI Demo (picking four cards) DeckOfCards Run rights reserved 9 rights reserved 4 Problem: Deck of Cards This problem builds a foundation for future more interesting and realistic applications: http://wwwcsarmstrongedu/liang/anim See Exercise 215 ation/web/24pointhtml Companion Website Problem: Lotto Numbers Suppose you play the Pick-1 lotto Each ticket has 1 unique numbers ranging from 1 to 99 You buy a lot of tickets You like to have your tickets to cover all numbers from 1 to 99 Write a program that reads the ticket numbers from a file and checks whether all numbers are covered Assume the last number in the file is Run 24 Point Game Lotto Numbers Sample Data LottoNumbers Run rights reserved 41 rights reserved 42

Companion Website iscovered [] [1] [2] [] [97] [98] Problem: Lotto Numbers iscovered iscovered iscovered [] [1] [2] [] [97] [98] true [] [1] [2] [] [97] [98] true true [] [1] [2] [] [97] [98] true true true iscovered [] true [1] true [2] true [] [97] [98] true Copying Arrays Often, in a program, you need to duplicate an array or a part of an array In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1; (a) (b) (c) (d) (e) rights reserved 4 rights reserved 44 Using a loop: Copying Arrays int[] sourcearray = {2,, 1, 5, 1; int[] targetarray = new int[sourcearraylength]; for (int i = ; i < sourcearrayslength; i++) targetarray[i] = sourcearray[i]; The arraycopy Utility arraycopy(sourcearray, src_pos, targetarray, tar_pos, length); Example: Systemarraycopy(sourceArray,, targetarray,, sourcearraylength); rights reserved 45 rights reserved 46 Peer Instruction 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 public class LinearSearch { /** The method for finding a key in the list */ public static int linearsearch(int[] list, int key) { for (int i = ; i < listlength; i++) if (key == list[i]) [] [1] [2] return i; list return -1; key Compare key with list[i] for i =, 1, rights reserved 47 rights reserved 48

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 Key Linear Search Animation List 6 4 1 9 7 2 8 6 4 1 9 7 2 8 6 4 1 9 7 2 8 6 4 1 9 7 2 8 6 4 1 9 7 2 8 6 4 1 9 7 2 8 rights reserved 49 rights reserved 5 Linear Search Animation http://wwwcsarmstrongedu/liang//web/linear Searchhtml From Idea to Solution /** The method for finding a key in the list */ public static int linearsearch(int[] list, int key) { for (int i = ; i < listlength; i++) if (key == list[i]) return i; return -1; Trace the method int[] list = {1, 4, 4, 2, 5, -, 6, 2; int i = linearsearch(list, 4); // returns 1 int j = linearsearch(list, -4); // returns -1 int k = linearsearch(list, -); // returns 5 rights reserved 51 rights reserved 52 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 eg, 2 4 7 1 11 45 5 59 6 66 69 7 79 The binary search first compares the key with the element in the middle of the array 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 rights reserved 5 rights reserved 54

Binary Search Binary Search Animation http://wwwcsarmstrongedu/liang//web/binary Searchhtml Key 8 8 8 List 1 4 6 7 8 9 1 4 6 7 8 9 1 4 6 7 8 9 rights reserved 55 rights reserved 56 Binary Search, cont key is 54 Binary Search, cont low mid high key > 5 key < 66 key < 59 list list list [] [1] [2] [] [4] [5] [6] [7] [8] [9] [1] [11] [12] 2 4 7 1 11 45 5 59 6 66 69 7 79 low mid high [] [1] [2] [] [4] [5] [6] [7] [8] [9] [1] [11] [12] 59 6 66 69 7 79 low mid high [7] [8] 59 6 low high rights reserved 57 [6] [7] [8] 59 6 rights reserved 58 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 -insertion point - 1 The insertion point is the point at which the key would be inserted into the list From Idea to Soluton /** Use binary search to find the key in the list */ public static int binarysearch(int[] list, int key) { int low = ; int high = listlength - 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; rights reserved 59 rights reserved 6

The ArraysbinarySearch 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 javautilarrays class For example, the following code searches the keys in an array of numbers and an array of characters int[] list = {2, 4, 7, 1, 11, 45, 5, 59, 6, 66, 69, 7, 79; Systemoutprintln("Index is " + javautilarraysbinarysearch(list, 11)); Return is 4 Sorting Arrays Sorting, like searching, is also a common task in computer programming Many different algorithms have been developed for sorting This section introduces a simple, intuitive sorting algorithms: selection sort char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'; Systemoutprintln("Index is " + javautilarraysbinarysearch(chars, 't')); Return is 4 (insertion point is, so return is --1) For the binarysearch method to work, the array must be pre-sorted in increasing order rights reserved 61 rights reserved 62 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 Selection Sort Animation http://wwwcsarmstrongedu/liang//web/selecti onsorthtml rights reserved 6 rights reserved 64 From Idea to Solution for (int i = ; i < listlength; i++) { select the smallest element in list[ilistsize-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position // The next iteration apply on list[i+1listsize-1] list[] list[1] list[2] list[] list[] list[1] list[2] list[] list[] list[1] list[2] list[] list[] list[1] list[2] list[] list[] list[1] list[2] list[] list[] list[1] list[2] list[] list[1] list[1] list[1] list[1] list[1] list[1] for (int i = ; i < listsize; i++) { select the smallest element in list[ilistsize-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position // The next iteration apply on list[ilistsize-1] Expand double currentmin = list[i]; int currentminindex = i; for (int j = i+1; j < listlength; j++) { if (currentmin > list[j]) { currentmin = list[j]; currentminindex = j; rights reserved 65 rights reserved 66

for (int i = ; i < listsize; i++) { select the smallest element in list[ilistsize-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position // The next iteration apply on list[ilistsize-1] Expand double currentmin = list[i]; int currentminindex = i; for (int j = i; j < listlength; j++) { if (currentmin > list[j]) { currentmin = list[j]; currentminindex = j; for (int i = ; i < listsize; i++) { select the smallest element in list[ilistsize-1]; swap the smallest with list[i], if necessary; // list[i] is in its correct position // The next iteration apply on list[ilistsize-1] Expand if (currentminindex!= i) { list[currentminindex] = list[i]; list[i] = currentmin; rights reserved 67 rights reserved 68 The Arrayssort Method The ArraystoString(list) Method The ArraystoString(list) method can be used to return a string 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 javautilarrays class For example, the following code sorts an array of numbers and an array of characters representation for the list double[] numbers = {6, 44, 19, 29, 4, 5; javautilarrayssort(numbers); char[] chars = {'a', 'A', '4', 'F', 'D', 'P'; javautilarrayssort(chars); Java 8 now provides ArraysparallelSort(list) that utilizes the multicore for fast sorting rights reserved 69 rights reserved 7