0% found this document useful (0 votes)
11 views29 pages

07 Arrays

جافا برمجة

Uploaded by

amrnadi999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

07 Arrays

جافا برمجة

Uploaded by

amrnadi999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 7

Single-Dimensional Arrays
Opening Problem
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.

1
Introducing Arrays
Array is a data structure that represents a collection of the same types
of data. Once an array is created, its size is fixed. An array reference
variable is used to access the elements in an array using an index.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5

Array reference myList[2] 3.3


variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123
2
Declaring Array Variables
datatype[] arrayRefVar;
Example: double[] myList;
datatype arrayRefVar[]; // This style is allowed,
but not preferred
Example: double myList[];

Creating Arrays
arrayRefVar = new datatype[arraySize];
Example: myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
3
Declaring and Creating in One Step
datatype[] RefVar = new datatype[arraySize];
Ex. double[] myList = new double[10];
datatype RefVar[] = new datatype[arraySize];
Ex. double myList[] = new double[10];

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
▪ The array elements are accessed through the index. The array
indices are 0-based, i.e., it starts from 0 to RefVar.length-1.4
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.

5
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.
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;
6
Processing Arrays
▪ When processing array elements, you will often use a for loop—for
two reasons:
1. All of the elements in an array are of the same type. They are
evenly processed in the same fashion repeatedly using a loop.
2. Since the size of the array is known, it is natural to use a for loop.
▪ (Initializing arrays with input values)
▪ (Initializing arrays with random values)
▪ (Printing arrays)
▪ (Summing all elements)
▪ (Finding the largest element)
▪ (Finding the smallest index of the largest element)
▪ (Shifting elements)

7
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

Initializing arrays with random values


for (int i = 0; i < myList.length; i++)
myList[i] = Math.random() * 100;

Printing arrays
for (int i = 0; i < myList.length; i++)
System.out.print(myList[i] + " "); 8
Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) total += myList[i];

Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++)
if (myList[i] > max) max = myList[i];

9
Finding the smallest index of the
largest element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++)
if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
10
Shifting Elements

11
Case Study: Analyzing Numbers
Write a program that finds the number of items above the average of all items.

12
Copying Arrays
To copy the contents of one array into another, you have to copy the
array’s individual elements into the other array.
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;
After this statement, list1 and list2 reference to the same array

13
Copying Arrays
There are three ways to copy arrays:
■ Use a loop to copy individual elements one by one.
■ Use the static arraycopy method in the System class.
■ Use the clone method to copy arrays; this will be introduced in
Chapter 13, Abstract Classes and Interfaces.

Using 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];

14
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
The parameters src_pos and tar_pos indicate the starting positions in
sourceArray and targetArray, respectively. The number of elements
copied from sourceArray to targetArray is indicated by length

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);

15
Passing Arrays to Methods
When passing an array to a method, the reference of the array is passed
to the method

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);

16
Pass By Value
▪ 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.
17
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 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]);
}

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]
}
}
18
Call Stack
Stack Heap
Space required for
method m
int[] numbers:reference
The arrays are
int number: 1 0 stored in a
0 heap.
Space required for the
main method
int[] y: reference Array of
int x: 1 0 ten int
values is

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.
19
Call Stack
Stack Heap
Space required for
method m
int[] numbers:reference
The arrays are
int number: 1001 5555 stored in a
0 heap.
Space required for the
main method
int[] y: reference Array of ten int
int x: 1 values is stored here
0

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.

20
Returning an Array from a Method
When a method returns an array, the reference of the array is returned.

21
Searching Arrays
Searching is the process of looking for a specific element in an array
Searching is a common task in computer programming.
There are many algorithms and data structures devoted to searching.
Two commonly used approaches are discussed, linear search and
binary search.
Linear Search

22
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.
The binary search first compares the key with the element in the middle
of the array.
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.
23
Binary Search, cont.
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
low mid high

[0] [1] [2] [3] [4] [5]


key > 7 list 2 4 7 10 11 45

low mid high

[3] [4] [5]


key == 11 list 10 11 45

24
key is 54 Binary
low Search,midcont. 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

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66 list 59 60 66 69 70 79

low mid high

[7] [8]
key < 59 list 59 60

low high

[6] [7] [8]


59 60

25
Binary Search Program
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;
} 26
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces an intuitive
sorting algorithm: selection sort.

Selection Sort
Suppose that you want to sort a list in ascending order.
Selection sort finds the smallest number in the list and
places it first. It then finds the smallest number remaining
and places it next to first, and so on, until only a single
number remains..

27
Selection Sort

28
Selection Sort

29

You might also like