Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
10.0 Introduction
One-dimensional array can be regarded as a linear list of same type data variables,
which can be declared as --
data-type variable-name[ n ];
This declaration is not sufficient. Along with such declaration, allocation for physical
memory space is also got be ensured. For that, we have to make use of new operator as
shown below: -
month = new String[12]; ......(b)
--- since there are 12 months in a year, the size is set to 12 to store the names of respective
months. We see that there are two steps involved in creating an array – i) to declare an
array variable with size and ii) to allocate memory to hold that array using new operator.
Above mentioned two steps can be combined together as...
Once an array is created, any particular element of it can be referred by specifying the
index of that element. Array index counts starts with zero. For example, different
elements of the array month[12] can be initialized in a way shown below.
month[0] = “January”;
month[1] = “February”;
|
|
month[10] = “November”;
month[11] = “December”;
In example -10.1, you can see a complete program using array declaration, storage
allocation and initialization of array elements one after another.
If you compile and execute this program, the output will appear as shown below: --
However, the three steps of array’s declaration, allocation and initialization can be
merged together as a single statement as shown in example 10.2.
The same output will be observed if you run this new program version.
1) An array always deals with a fixed sized (as declared) collection of data elements.
2) Data elements must be of the similar data types.
3) Element count starts from 0.
4) Array elements are placed in contiguous (with no gap in between) memory locations.
5) If each element takes 4 bytes, then an array of size 20 will occupy a memory space of 80
bytes only.
6) An array can be regarded as a static (fixed size) data structure.
You can declare a (4rows by 12 columns) two dimensional array, named sales, in
the following way –
Once sales figures are stored in such an array structure, calculations of grand-total,
individual total, average marketing capacity, differences from the sales target, etc can be
found out very easily.
Now we will examine how arrays can make computational work much easier and
simpler.
Averaging – for estimation of the average of a group of data values, which can be
stored as elements of an array and each element can be called and used simply by specifying
the array name and the respective index number.
Comparing, insert/modify values of any element at random can be done for data
processing if relevant data remain stored in the form of an array.
Determination of Max/Min value from any array elements is quite simple. Thus
structuring results data in the form of an array can help preparing Merit List of any
examination very easily.
Random Access – Any element of an array, whether the first, middle or the last
element, can be accessed with the same ease and speed. This is a very useful programming
feature.
A few examples now can show how easily you can make use of an array to
manipulate a group of data elements for extracting useful information.
/* Monthly sales figures for four persons are stored in a two dimensional array
and quarterly total for each person is stored in another single dimensional array */
sales[1][0] = 6710.00;
sales[1][1] = 4329.50;
sales[1][2] = 3988.00;
sales[2][0] = 4433.00;
sales[2][1] = 3876.50;
sales[2][2] = 3981.50;
sales[3][0] = 3987.00;
sales[3][1] = 4533.00;
sales[3][2] = 4387.00;
}
}
Example 10.5 To Compare first or last element with other Elements of an array
/* First element of an array is compared with all other elements one by one and
the result of comparison – lower or higher – is printed out */
In this example you find that three integer values are inserted at random positions,
first at index position 6, second at index position 1 and third at index position 4. Other
positions are kept vacant. Execute this program to see the output (Picture 10.1). Extend this
program to fill up all the remaining vacant positions.
Picture 10.1
Here two very common sorting algorithms will be discussed. First about the
Selection sort and then about the Bubble sort.
This algorithm is most suitable when data values are placed in an array of single
dimension. Here the smallest element is searched out and placed in the first index position
(for ascending order) of the array by exchanging their respective locations. Next the smallest
of the remaining elements is searched out and then placed in the second position. In this way
all other remaining elements are searched out and placed in their respective positions
maintaining proper order.
In this sorting technique, the minimum element (of the unfixed list) is
selected and placed in its appropriate position – one after another. Thus the unfixed list
length gradually decreases along with the number of comparisons required. For this reason
the name -- Selection or Selection-exchange Sort -- has been given to this algorithm.
For sorting in the descending order, the largest element is searched and placed in the
first index position. The process is looped until all the elements are arranged in the
descending order.
Two programs, one for ascending and another for descending, will now be shown. The
algorithms will be explained thereafter.
temp = a[i];
a[i] = a[position]; // Positions exchanged to place
// Pass-minimum at its proper place
a[position] = temp;
}
System.out.println( "Positions exchanged with minimum = " + min);
// Minimum w.r.t. to a particular Pass
}
System.out.println (" Ascending order list is ::");
for (int k=0; k < size; k++)
System.out.print (a[k] + " ");
}
}
Begin;
Step1: Store Array elements- a[N]; Find array size; initialize instance variables;
Step2: Start Looping -- Find location of the smallest element in the array and then
Interchange the position of the smallest element with that found at a[0];
Step3: Find the location of the next smallest element from the sub-list of N-1 elements and
interchange it with that found at a[1].
Step4: Go on repeating Step-3 for sub-lists of lengths N-2, N-3, .. .., 2 elements for placing
the minimum of the respective-Pass at the proper location of the array.
End.
Now look at the output of example-10.8. After pass –0, minimum element (i.e. 1) gets the
first position; after pass-1 next minimum (i.e. 4) gets the second position; and in this way....
the largest element (i.e. 45) gets the last position. Thus a sorted list in the ascending order
is obtained and printed out.
By running this program you will get the output as: ---
96 80 76 55 54 44 39 23
The Bubble sort is another sorting algorithm where two adjacent elements of a list is
compared and exchanged if they are not in order. This comparison [to place smaller valued
element on top] process is continued for the entire list until no further exchange is found
possible. This completes a single pass in which the largest element gets its final position at
the bottom of the list.
In the second pass, the process of comparison and interchange between adjacent
elements is continued up to the last but one position in the list, because the last position has
already been filled up with the largest element in the first pass. After this pass, the second
largest element gets the place in the second place from the bottom. The process continues
until the smallest element gets the top most position in the list.
You have seen bubbles to move up in a liquid. Consider the smallest element as a
bubble in an array list. As a bubble moves up in a liquid, so a smaller element gradually
moves up in such an array list when bubble sort is applied. The name bubble sort is given to
this algorithm because of this behaviour of the method.
Begin;
Step-1: Array a[N]is read and stored; instance variables initialized;
Step-2: Adjacent comparisons –a[0] with a[1] and placing smaller one on top is
continued until a[N-1] < a[N] condition is reached. This is the first pass in which
the largest element of the list is placed at the bottom.
Step-3: Go on repeating Step-2 for sub-lists of N-1, N-2, N-3,....., 2 elements until
the smallest element gets the top position of the array. There will be altogether (N-1)
number of Passes to sort a list of size N.
End.
Assignment – Rewrite the Bubble sort algorithm to sort an array in the descending order.
10.3 Searching in Sorted Arrays
However, if the list remains sorted, the searching process becomes very efficient as you
have seen in a Dictionary. In a Dictionary, words remain sorted alphabetically and that is
why searching for any word from anywhere becomes so easy and quick. That is why to
make searching efficient, lists to be searched are maintained in sorted order. Binary search
is the technique, which can be applied on sorted lists only.
The element to be searched is often called -- the Key. In a binary search, the
middle element of the list is taken out and compared with the key. If key value is lower
than the middle element value, then the lower half portion of the list is only taken into
consideration; otherwise the upper half portion is considered. This technique is continued
until either the match with the key if found out or it is reported that the key is not present
in the list.
Before going into any further details, we will examine first one program implementing
Binary Search.
Try with a different key value [either present or absent in the list] and observe what output
do you obtain and why.
Begin;
Step1: Initialize lower_bound(lb), higher_bound(hb) and the done flag;
Step 5: When Success Flag not set -- report that the key is not present in the
list.
End.
(Compare the algorithmic steps with the program codes shown in example- 10.11)
There is one special class, called Object, in Java. All other classes can be regarded
as sub-classes of this Object class. This means that a reference variable of type Object can
refer to the objects of any other class types. Since arrays can be implemented as classes, a
variable of type Object can also refer to an array.
Object class can be regarded as a superclass of all other classes in java. It defines a
number of methods, which are mentioned below:
In BlueJ environment, you can see these methods displaced under the menu head
“ inherited from object “ (Picture 10.2) when an object gets created from a defined class.
From a class definition, many objects can be created because the superclass Object
is capable of cloning itself by calling its clone () method. No further discussions on this
topic will be made here to keep the beginners free from the burden of advanced concepts in
java.
However, how an array containing elements of different data types can be created
using the class Object will be shown here as a demonstration only.
}
}
Execution of this program will show the output :--
The Object type array is a reference type array and stores the references of the
array elements. Since Strings are always stored as references to char arrays, they are
displayed as it is, but references to integer and float values are nothing but addresses of the
locations where they are stored. Therefore, those addresses are displayed as output.
Remember that int and double type arrays behave as normal arrays. Advanced users may
extract benefits out of these Object class methods.
10.5 Conclusions
This chapter has dealt with arrays and their applications in solving many day-to-day
problems. Arrays are fixed size linear data structures from where elements can be retrieved
by specifying their index value(s). With a good number of examples the importance of
arrays have been shown.
Sorting a list of values is very often required. Two sorting algorithms have been
explained with examples.
The advantage of binary search over sequential search has also been shown.
The concept of superclass Object and its importance of the clone () and other
methods has been touched upon for advanced users. How an array can maintain references
to created objects has also been discussed.