Java Reference

In-Depth Information

int
x= numberLess(d, d[0]);

stores
1
in
x
because one element of
d
is less than
d[0]
.

The method body must process array segment
b[0..b.length-1]
, so we

use this loop schema for processing an array segment:

//
Process elements of
c[h..k-1]
, in order

//
inv:
h≤i≤k
and
c[h..i-1]
has been processed

for
(
int
i= h; i != k; i= i + 1) {

Process
c[i]

}

Instead of array
c
,
we have
b
; instead of
h
, we have
0
; and instead of
k
we have

b.length
:

//
Process elements of
b[0..b.length-1]
, in order

//
inv:
0 ≤ i ≤ b.length
and
b[0..i-1]
has been processed

for
(
int
i= 0; i != b.length; i= i + 1) {

Process
b[i]

}

What does it mean to process an element
b[i]
? If the element is less than

v
, we want to count it, so we need a variable
n
to accumulate the result:
n
is the

number of elements in segment
b[0..i-1]
that are less than
v
, so “Process

b[i]
” means to add
1
to
n
if
b[i]
is less than
v
.

What value should
n
have initially? At the beginning, no elements have been

processed, so
n
must be initialized to
0
.

The final step is to return
n
.

This ends the development. See Fig. 8.2 for the complete function.

See lesson 8-3

to get this pro-

gram.

Activity 8-3.5

shows you how

to test it.

/** =
number of elements of
b
that are less than
v */

public static int
numberLess(
int
[] b,
int
v) {

int
n= 0; //
number of elements less than
v
in
b[0..j-1].

//
Process elements of
b[0..b.length-1]
, in order

//
inv:
0 ≤ i ≤ b.length
and the definition of field
n

for
(
int
i= 0; i != b.length; i= i + 1) {

if
(b[i] < v)

{ n= n + 1; }

}

return
n;

}

Figure 8.2:

Function
numberLess

Search WWH ::

Custom Search