Class and Object

Download Report

Transcript Class and Object

Array







Must declare a variable to reference the
array
double [] mylist; // cannot double list[20];
Or double mylist[];
The declaration doesn’t allocate memory
until you create an array by
mylist = new double[200];
For( int I = 0; I < mylist.Length; i++)
mylist[i] = 2*I;
Array initializer

Combine declaring an array, creating
an array, and initializing in one
statement


double [] myList = {1.9, 2.9, 3.4, 3.5};
When processing array elements, you
will often use a for loop
Passing array to a method










public static void doArray(int[] array)
{
for( int i = 0; i < array.Length; i++)
{
array[i] = array[i] +1;
}
}
Difference between passing the values of primitive
data types and passing arrays
Primitive data type: passed by value
Array: passed by reference
Searching array



Searching is the process of looking for a
specific element in an array
Linear search approach compares the key
element sequentially with each element in
the array.
Continue to do so until the key matches an
element in the array or the array is
exhausted without a match being found
Linear search method










Public class LinearSearch{
public static int LinearSearch(int [] list, int key){
for( int I = 0; I < list.length; i++)
{ if ( key == list[i])
return I;
}
return -1;
}
}
This method return the index where the key
element found, and return -1 if not found
Sorting array

Selection sort: suppose that you want
to sort a list in ascending order.
Selection sort finds the largest number
in the list and place it last. It then finds
the largest number remaining and
places it next to the last, and so on
until the list contains only a single
number.



















Public class SelectionSort{
public static void selectionSort( double[] list){
for ( int I = list.legth-1; i>=1; i--){
double currentMax = list[0];
int currentMaxIndex = 0;
for(int j =1; j <=I;j++){
if(currentMax <list[j]){
currentMax = list[j];
currentMaxIndex = j;
}
}
// swap
if ( currentMaxIndex != i){
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
}
}
Assignment

Write a program that





Create an array of integer with size 2
Pop input dialog twice to ask user to
enter two numbers
Convert numbers to int and store in the
array
Write a method to swap the array
Print out the new array ( terminal or
messagedialog)