Sie sind auf Seite 1von 19

Modules: Print Module

https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
Send to Printer | Close Window

Lesson 4: Arrays
Lesson 4: Arrays
Lesson 4: Arrays
Objectives
Objectives
Objectives
In this lesson you will learn to:
For the Android application

Creating lists using arrays.

For the Java coding

Write a single-dimensional array in a J ava program using primitive data types

Write a single-dimensional array in a J ava program using reference (Object) types.
In more specific details you will learn how to


Declare an array, initialize an array, and traverse the array

Describe array initialization

Understand the different sorting algorithms

Understand the different search algorithms

Apply J ava's sort and search algorithms

Purpose
Learning how to use arrays will help the java programmer create groups of similar data types for sort and manipulation in a program.
Arrays can be used to store coordinates for a shape, locations on a map, or simulate a maze. Arrays can hold list of prices, rows returned from a database,
or top search results. Understanding how to create, initialize, and traverse arrays is a critical step in becoming a skilled programmer.
In this lesson you will learn how to declare, initialize, and iterate through an array. You will also learn how to use an array for practical use.


Lists in Android
Lists in Android
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
Creating lists in Android
Lists are one of the more common design patterns used in mobile applications.
As with buttons, that triggered an activity, lists allow us to open activities as well, such as articles, web browser, maps, etc.
To illustrate lists you are going to create an application that displays the attractions in your area.
But, to create lists in an application, we need to know more about arrays.
Thus, before we learn how to create lists, we need to investigate how arrays work first.

Arrays
Arrays
What is an array?

During your first year, in ICT1511, ICT1512 and ICT1513 you have addressed and implemented arrays. If you cannot remember exactly how an array works, then it is
advisable that you first refer back to your first year level topics where arrays were explained. Below is a quick overview:

An array is a collection of values of the same data type stored in a container object.
Can be any number of values
Length of the array is set when the array is declared
Size is fixed once the array is declared

Every value is called an element
Each element is accessed by an index
Index must be an integer
Index always starts at 0
Can contain any data type
Primitive
Pre-defined Objects (such as Strings)
Self-Defined Objects (Instances of a class you create!)
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]


Creating an array

Arrays allow access to the data, e.g. "green", "blue", "black", etc. by referring to the numeric index. Thus, should I wish to refer to the data "black", then I
will refer to Colour[3]. Note "black" is the fourth element in the array, but the index number is "3". This is very important to remember.
Going back to our application that we would like to create for our local town.
I am living in Roodepoort and have identified the following attractions, amongst others:
1. Walter Sisulu National Botanical Garden
2. Coca-cola dome
3. Promusica Theater
4. UNISA Science Campus
Let's add these attractions to a list:
Attraction[0] ="Walter Sisulu National Botanical Garden"
Attraction[1] ="Coca-cola dome"
Attraction[2] ="Promusice theater"
Attraction[3] ="UNISA Science Campus"
In my application, I am going to link the user to the individual websites for these attractions.

Arrays: declaring
Arrays: declaring
Declaring an array
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
There are 3 parts to declaring an array:
Data type
Variable name
Array size


Array declarations:
There are two distinct ways in which an array can be declared:
1. The items are known beforehand
If the items are known beforehand,.
dat a_t ype[ ] var i abl e_name = {i t em1, i t em2, i t em3, . . . , i t eml ast };
Example 1: an array for the days of the week:
St r i ng[ ] weekdays = {" Monday" , " Tuesday" , " Wednesday" , " Thur sday" , " Fr i day" , " Sat ur day" , " Sunday" };
Example 2: the number of days in each month for 2014
i nt [ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
2. The items are not known and will be entered during the execution of the program
If the items are not known beforehand then the array declaration can be done in either one or two lines:

In two lines:
dat a_t ype[ ] var i abl e_name;
var i abl e_name = new dat a_t ype[ si ze] ;

Or in one line:
dat a_t ype[ ] var i abl e_name = new dat a_t ype[ si ze] ;
Note that both of these syntax examples are equivalent array declarations.

Declaring an array for our Attractions
Create a new Andr oi d Appl i cat i on and call it Ar r ays.
Add a But t on and a Text Vi ewwidget.
Add the usual code to link the widgets to the code.
We will now add the code to create the array within the code for the button.
Create the array: MyAttractions
For this example, we are going to enter the attractions that we have identified for our local town.
Because I know the entries beforehand, I am going to add them to the array declaration upfront:
Below is an extract from the code:
But t on but Show = ( But t on) f i ndVi ewByI d( R. i d. bt nShow) ;
f i nal Text Vi ew f Show = ( Text Vi ew) f i ndVi ewByI d( R. i d. t xt Show) ;

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
but Show. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
String[] myAttractions =
{"Walter Sisulu National Botanical Garden",
"Cocal-Cola Dome",
"Promusica Theatre",

"UNISA Science Campus"};

}/ / end of onCl i ck
}) ; / / but Show
An alternative way that you could have applied:
Declare the array and then add the items one by one.
Below is an extract of such code (replacing the above code)

String[] myAttractions = new String[4];
myAttractions[0] = "Walter Sisulu National Botanical Garden";
myAttractions[1] = "Cocal-Cola Dome";
myAttractions[2]= "Promusica Theatre";

myAttractions[3]= "UNISA Science Campus";

Display the array values in the TextView widget on your screen
To test that our array is working correctly.
Add the following code that will display (randomly) any one of the items in your array.
Below is the complete code to help you:
@Over r i de
pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) {
super . onCr eat e( savedI nst anceSt at e) ;
set Cont ent Vi ew( R. l ayout . act i vi t y_mai n) ;
/ / Li nk t he wi dget s t o t he code

But t on but Show = ( But t on) f i ndVi ewByI d( R. i d. bt nShow) ;

f i nal Text Vi ew f Show = ( Text Vi ew) f i ndVi ewByI d( R. i d. t xt Show) ;
final Random randomGenerator = new Random();

but Show. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go

St r i ng[ ] myAt t r act i ons = new St r i ng[ 4] ;
myAt t r act i ons[ 0] = " Wal t er Si sul u Nat i onal Bot ani cal Gar den" ;
myAt t r act i ons[ 1] = " Cocal - Col a Dome" ;
myAt t r act i ons[ 2] = " Pr omusi ca Theat r e" ;
myAt t r act i ons[ 3] = " UNI SA Sci ence Campus" ;

/ / di spl ay any on of t he el ement s on t he scr een

int random = randomGenerator.nextInt(4);
String sDisplay = myAttractions[random];
fShow.setText(sDisplay);


}/ / end of onCl i ck
}) ; / / but Show
}
Save, correct any others and run the code.
If you really struggle, then download an example of the code from myUNISA, Additional Resources.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
Android: using arrays and lists
Android: using arrays and lists
Activity
Using arrays and Lists in Android
We are now ready to develop an Android application that will use Lists.
There will be some new "coding" that we will be doing, thus take care that you follow the steps very carefully.
Step 1:
Create a new Android Application. Save it as MyTown.
Don't add any widgets at this stage.
Step 2:
In Mai nAct i vi t y. j ava do the following:
1) Remove the extend: Act i vi t y and replace it with Li st Act i vi t y
publ i c cl ass Mai nAct i vi t y ext ends ListActivity {
2) Scroll up and expand the i mpor t s.
Add the following import: i mpor t andr oi d. app. Li st Act i vi t y;
Remove the import: i mpor t andr oi d. app. Act i vi t y;
3) Remove: set Cont ent Vi ew( R. l ayout . act i vi t y_mai n)
Step 3:
Now we are ready to add our array. J ust is in the previous example, create an array, call it myAttractions. Create the array and the elements.
(Warning: if you do decide to copy and past the code from the previous example, then first copy it to an independent text editor, such as notepad. From
there you can copy and paste into your code. J ava sometimes have this annoying feature where it copies some of the imports with and it can really mess-
up your code.)
Below is an extract of the code:

i mpor t andr oi d. os. Bundl e;
i mpor t andr oi d. vi ew. Menu;
i mpor t andr oi d. wi dget . Ar r ayAdapt er ;
import android.app.ListActivity;

publ i c cl ass Mai nAct i vi t y ext ends ListActivity {
@Over r i de
pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) {
super . onCr eat e( savedI nst anceSt at e) ;
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
/ / My codi ng goes her e
/ / Decl ar i ng t he ar r ay and i t ems

String[] myAttractions = new String[4];
myAttractions[0] = "Walter Sisulu National Botanical Garden";
myAttractions[1] = "Cocal-Cola Dome";
myAttractions[2]= "Promusica Theatre";
myAttractions[3]= "UNISA Science Campus";
}
Step 4:
The next step is to set the Li st Adapt er.
After you've created the array, enter the following line of code that will display the myAt t r act i ons array in a generic Li st Vi ewlayout on the screen:

setListAdapter(new ArrayAdapter
(this, android.R.layout.simple_list_item_1, myAttractions));
Now you can save, check for errors and run the code.

If everything works correctly you should get a screen similar to the following:



Step 5:
Let's add images to our application. If you have images available,
either in .png or .jpg format, drag these images to the drawable-mdpi
folder. Select copy when requested.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
I have five images available as
well as one (roodepoort.jpg) that I am going to use as the image when my
application is started.
Remove the default image i ct _l auncher . j pg from the list.



To set the default image that will show when you start the application, you need to alter the Andr oi dMani f est . xml file.

Open the Andr oi dMani f est . xml file.
In
Applications, alter the entry for icon by removing the last part
(ic_launcher) and replacing it with the image of your choice:



Verify in Andr oi d. Mani f est . XML that it is updated according.

andr oi d: al l owBackup=" t r ue"
android:icon="@drawable/roodepoort"
andr oi d: l abel =" @st r i ng/ app_name"
andr oi d: t heme=" @st yl e/ AppTheme" >

SAVE and close the AndroidManifest Test

Step 5:

Often you would like to display your own title on the screen, instead of MyTown (the name of the application).

Under the r es folder, select val ues and the st r i ngs. xml .

Enter the name of your title bar in the field: Val ue*: Roodepoort.

Save, decode and run the application
At this stage your screen will look something similar to (it may look a
bit different if you are using BlueStack as the emulator)

Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]

Step 6
Almost done....
It is now the time to (just as with the RadioButtons) to add listeners to the options.
The method onLi st I t emCl i ck( ) is called when any of the items in the list is selected.
When an item in the list is selected, the position of the item is passed from the onLi st I t emCl i ck( ) and then, depending on the position an action is
performed.
We are going to use the swi t ch statement for this. (If you can't remember refer back to the IF and SWITCH lessons).
Add the following code that will calll the onLi st I t emCl i ck( ) method.

This code must go after:
set Li st Adapt er ( new Ar r ayAdapt er ( t hi s, andr oi d. R. l ayout . si mpl e_l i st _i t em_1, myAt t r act i ons) ) ; }
/ / code must go her e
and before
@Over r i de publ i c bool ean onCr eat eOpt i onsMenu( Menu menu) {


Enter the following code:

protected void onListItemClick(ListView l, View v, int position, long id){ }/ / onLi st I t emCl i ck

Hover the mouse on the underlined red commands and import the missing widget, alternatively under imports type in:
i mpor t andr oi d. wi dget . Li st Vi ew;
Complete the code:
pr ot ect ed voi d onLi st I t emCl i ck( Li st Vi ew l , Vi ew v, i nt posi t i on, l ong i d) {
switch(position){
case 0: {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.sanbi.org/gardens/walter-sisulu")));
break;
}
case 1: {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.coca-coladome.co.za")));
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
break;
}
case 2: {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.promusica.co.za")));
break;
}
default: {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.unisa.ac.za")));
}
}//switch
}
Save, decode, compile and run.
If you really struggle download the code from myUNISA. Note the code that is available in myUNISA has the code that we will be doing in the next slide
(adding another class (screen) to the application) included.


Using arrays and lists and adding another class
Using arrays and lists and adding another class
Using arrays and lists and adding another class
In the previous slides we've created lists based on ar r ays and via onLi st I t emCl i ck( ) method linked these different items in the list (array) to certain
actions or activities via st ar t Act i vi t y( ) .
I am going to show you now (we have done it previously with buttons), how to create a new screen, the new class for the screen and how to link the item in
the list to this screen.
To do this, go back to the original array that you've created and add one item to this list. Keep in mind that you need to indicate in the declaration of the
array that there are now 5 items:
St r i ng[ ] myAt t r act i ons = new St r i ng[5];
myAt t r act i ons[ 0] = " Wal t er Si sul u Nat i onal Bot ani cal Gar den" ;
myAt t r act i ons[ 1] = " Cocal - Col a Dome" ;
myAt t r act i ons[ 2] = " Pr omusi ca Theat r e" ;
myAt t r act i ons[ 3] = " UNI SA Sci ence Campus" ;

myAttractions[4] = "Medical information";
Call this item: Medical information.
Create a screen (refer back to the sections where we create multiple screens - or view my podcast on how to create multiple screens.)
For the purpose of this exercise I've added the names and telephone numbers of the local hospitals and clinics (all in TextView) as well as a BackButton to go back to
the Mai nAct i vi t y.
All that I need to now is to link an act i vi t y to the option.
In the swi t ch statement alter the third (3) case to open the correct website and add in the default option the following information:
swi t ch( posi t i on) {

case 0: {st ar t Act i vi t y( new I nt ent ( I nt ent . ACTI ON_VI EW,
Ur i . par se( " ht t p: / / www. sanbi . or g/ gar dens/ wal t er - si sul u" ) ) ) ;
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
br eak;
}
case 1: {st ar t Act i vi t y( new I nt ent ( I nt ent . ACTI ON_VI EW,
Ur i . par se( " ht t p: / / www. coca- col adome. co. za" ) ) ) ;

br eak;
}
case 2: {st ar t Act i vi t y( new I nt ent ( I nt ent . ACTI ON_VI EW,
Ur i . par se( " ht t p: / / www. pr omusi ca. co. za" ) ) ) ;

br eak;
}
case 3: {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.unisa.ac.za")));

break;
}
default : {startActivity(new Intent(MainActivity.this, MedicalInfo.class));
}
}/ / swi t ch

Save, correct any errors, compile and run the application.
You can download the complete application from myUNISA to compare your coding to.
.


Android: displaying the images next to each option
Android: displaying the images next to each option
Displaying the images next to each option
Before we end this lesson, there is just one more thing to do.
In the beginning we've added a number of image files to the drawable-mdpi file, but we haven't used them as yet.
We would like to display each image next to the item on the opening screen.
For this we will need to play around in the l ayout . xml file.
Open the l ayout : act i vi t y_mai n. xml in Graphical Layout view.
Change the layout to LinearLayout.
Open the act i vi t y_mai n. xml to view the XML content.
Alter the XML to represent the following XML:

andr oi d: l ayout _wi dt h=" f i l l _par ent "

andr oi d: l ayout _hei ght =" f i l l _par ent " >

andr oi d: i d=" @+i d/ roodepoort"
andr oi d: l ayout _wi dt h=" 50px"
andr oi d: l ayout _hei ght =" 50px"
andr oi d: l ayout _mar gi nLef t =" 4px"
andr oi d: l ayout _mar gi nRi ght =" 10px"
andr oi d: l ayout _mar gi nTop=" 2px"
andr oi d: sr c=" @dr awabl e/ roodepoort" >


Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]

andr oi d: i d=" @+i d/ t hel i st "
andr oi d: l ayout _wi dt h=" wr ap_cont ent "
andr oi d: l ayout _hei ght =" wr ap_cont ent "
andr oi d: t ext =" @+i d/ thelist"
andr oi d: t ext Si ze=" 25sp" >


Save the XML and verify that there are no errors.
There are two things that are important:
1) The id of the Text Vi ewwidget: thelist
2) The id of the i mage that will be displayed, viz: roodepoort
Open the MainActivity.java file and update the setListAdapter to point to our new XML file and not the generic XML file:
set Li st Adapt er ( new Ar r ayAdapt er ( t hi s, R. l ayout . act i vi t y_mai n,
R. i d. t hel i st , myAt t r act i ons) ) ;

Save, correct any errors and run the code.
When you run the code, you will notice that all the items in the list have the same image.
(I am working on a solution to display the different images for each item. Any suggestions and ideas welcome.)
Should you struggle, you can download the complete code for this application from myUNISA.



Arrays and objects
Arrays and objects
Arrays and objects
Arrays are not restricted to only storing primitive data types.
In fact, arrays can store any type of object, including types that you define, even classes.
I have created an application, CarHire to illustrate the use of classes and arrays.
Download from Additional Resources, the ZIPPED file, Car Hi r e. zi p.
Unzip the file into the folder where all your J ava applications are, e.g. I CT2612_apps.
Before your compile and run the code:
Open the main program and study it:
MainActivity.java
Then open the two classes:
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
First Driver.java
and then Car.java
Your task is to work through this code and understand it.
When you've worked through the code answer the questions in the Self Assessment.
The questions are based on the code for the application CarHire.
These will be typical questions that could be asked in the examination!



Accessing and manipulating arrays
Accessing and manipulating arrays
Accessing and manipulating arrays
There are a number of methods associated with arrays that you can use when dealing with arrays.
We will apply the following methods in our coding and discuss them below:
a) Determining the length of an array
b) Iterate (or traverse) through an array
c) Sort an array
d) Search through an array

Create a new Android Application
For this part of the lesson, create a new Android Application, call it Ar r ays2.
Create one screen, with one But t on and on Text Vi ewwidget.
For the Text Vi ewwidget, set the Li nes = 20 and the Wi dt h = 300dp.
The coding will go inside the block of code for the button.
We will display our results in the TextWidget field.
a) Determining the length of an array
Syntax: arr.lenght;
It is always important to know the length of an array. The length of an array is based on the number of user inputs into the array.
When you initialise an array, you must define the size or length for the array. This length is then stored as an instance varaible for the object and be
access using the notation ar r ayName. l engt h
Enter the following code in the block of code for the button.
St r i ng di spl ay=" " ; / / usi ng t hi s t o di spl ay i nf or mat i on
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
/ / cr eat e an ar r ay myFl ower s wi t h pr edef i ned el ement s.
St r i ng[ ] myFl ower s = {" Rose" , " Sunf l ower " , " Eucal ypt us" , " Dandel i on" , " Vi ol et " , " Li l y" };
i nt l enFl ower s = myFl ower s. l engt h; / / det er mi ne t he l engt h of t he ar r ay myFl ower s

di spl ay = di spl ay+" " +I nt eger . t oSt r i ng( l enFl ower s) ; / / add t hi s i nf o t o di spl ay
f Di spl ay. set Text ( di spl ay) ; / / di spl ay i nf o on t he scr een
Save, compile and run the code.
The number 6 will be displayed. This number indicates the number of elements in the array.
Keep in mind that the elements are numbered from 0. Thus myFl ower s[ 0] = " Rose" and myFl ower s[ 5] = " Li l y"
This is VERY important to remember, since the lenFlowers = 6 but the last element in the array =5.
b) Iterate (or travers) through the array
To iterate through, or traverse, an array means to progress through each element of the array by index number.
Iterating through an array can be useful when you wish to access each element of an array in order, or when you wish to initialize the elements of an array
as all the same value.
Let's add some code to iterate through our list of flowers and display it on the screen.
Add the following code just before your last line of coding:
f Di spl ay. set Text ( di spl ay) ; / / di spl ay i nf o on t he scr een
//traverse through the array
for (int i=0; i < lenFlowers; i++)
{display = display + " \n " + i + " " + myFlowers[i];}
f Di spl ay. set Text ( di spl ay) ; / / di spl ay i nf o on t he scr een
Save, compile and run the code.
Notice that in the first line the number of elements is displayed. Thereafter, line by line, the element number and the element in the array myFlowers are
displayed.
c) Sorting arrays
The next logic step will be to sort our array.
There are many different algorithms for sorting arrays, some are easier to code and some have a faster computation time.
Why sort an array?
In some cases, especially when searching for elements in an array, it is beneficial to sort your array in
lexicographical order. This could greatly reduce time spent searching through an array as you will see later.
The 3 main sorting algorithms for arrays are:
(1) Selection Sort
(2) Bubble Sort
(3) Merge Sort
An algorithm, in programming, is a logical computational procedure that if correctly applied ensures the solution of a problem which, in this case, is
sorting an array.

Lexicographical order is an order based on the ASCII value of characters. The table of values can be found at http://www.asciitable.com/
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]

The three types of sorts discussed below in short.
(1) Selection Sort
Selection sort is a sorting algorithm that is known for it's simplicity.
The algorithm works as follows:
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each
time)
But: Selection sort can be very inefficient on large arrays because in the worst case it would have to iterate
through the entire array each time to find the next smallest element. This algorithm may be preferred for smaller arrays because of its simplicity.
Consider having an array: {5 , 7, 2, 15, 3|
Step 1 of the selection sort algorithm is to find the smallest value, which is 2.
Step 2, swap the value with the first position, which would give us: {2, 7, 5, 15, 3}
Repeating these steps we find that 3 is the next smallest number, when we swap it for the next position we get: {2, 3, 5, 15, 7}
We would repeat this until the array is sorted or to be more specific when we reach array.length -1 at which point if the second last element was smaller than the last
we would swap and the array would be sorted otherwise the array is sorted {2, 3, 5, 7, 15}
(2) Bubble Sort
Bubble sort, also known as exchange sort, is another sorting algorithm that is fairly simple but very inefficient on large lists.

The algorithm works as follows:

1. Compare 2 adjacent values (those at indexes 0 and 1)
2. If they are in the wrong order, swap them
3. Continue this with the next two adjacent values (those at indexes 1 and 2) and on through the rest of the list
.
4. Repeat steps 1 through 3 until array is sorted.
This video is a great visual representation of how this algorithm works: http://www.youtube.com/watch?v=lyZQPjUT5B4

Consider this array:{40, 7, 59, 4, 1}
Following the steps of the algorithm, after the first step of comparing and swapping the first two values we have: {7, 40, 59, 4, 1}
Then we compare and swap the next two values and get: {7, 40, 59, 4, 1}
Notice that the swap didn't occur in the second comparison. This is because they are already in the correct order.
These steps are repeated until finally we get a sorted array:{1, 4, 7, 40, 59}


(3) Merge Sort
Merge Sort is a little more complex than the previous two sorting algorithms, but it can be much more efficient by taking advantage of parallel processing.
Merge Sort takes on a divide and conquer technique, which allows it to sort arrays with optimal speed.
The algorithm works as follows:

1. Divide the unsorted list into sublists, each containing 1 element (a list of 1 element is considered sorted).
2. Repeatedly Merge sublists to produce new sublists until there is only 1 sublist remaining. (This will be
the sorted list.)
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
You are welcome to view the sample code and learn more about Merge Sort at: http://www.roseindia.net/java/beginners/arrayexamples/mergeSort.shtml
For the purpose of this course, it is important to understand the different types of sorting methods, but since we are living in the 21st age and since we
are using J ava, we will be using one of J ava's own methods created specifically for this purpose.
Sorting an array in ascending order (small to large, a to Z):
Ar r ays. sor t ( myFl ower s) ;
Sorting an array in descending order (large to small, Z to a):
Ar r ays. sor t ( myFl ower s, Col l ect i ons. r ever seOr der ( ) ) ;
Let's apply it to our coding.
Before the for loop, enter the following code:
St r i ng di spl ay=" " ; / / usi ng t hi s t o di spl ay i nf or mat i on
/ / cr eat e an ar r ay myFl ower s wi t h pr edef i ned el ement s.
St r i ng[ ] myFl ower s = {" Rose" , " Sunf l ower " , " Eucal ypt us" , " Dandel i on" , " Vi ol et " , " Li l y" };
i nt l enFl ower s = myFl ower s. l engt h; / / det er mi ne t he l engt h of t he ar r ay myFl ower s

di spl ay = di spl ay+ " \ n" +I nt eger . t oSt r i ng( l enFl ower s) ; / / add t hi s i nf o t o di spl ay
Arrays.sort(myFlowers); //sorting the array in ascending order
/ / t r aver se t hr ough t he ar r ay
f or ( i nt i =0; i < l enFl ower s; i ++)
{di spl ay = di spl ay + " \ n " + i + " " + myFl ower s[ i ] ; }
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
f Di spl ay. set Text ( di spl ay) ; / / di spl ay i nf o on t he scr een
Save, compile and run.
You will now see the list displayed in ascending order.
Do the same, but replace the code with Ar r ays. sor t ( myFl ower s, Col l ect i ons. r ever seOr der ( ) ) ;
d) Searching through arrays
Now that you are familiar with a few sorting algorithms, you can implement those prior to searching for an element in an array.

Sorting an array makes searching faster and easier.
There are two basic searching methods:

(1) Sequential searches
(2) Binary searches
Consider having a sorted array of the names of students in your and you want to find out if J uan is in your class. You could perform a search on your
array of names and find the answer. You could also find out exactly where his name lies in alphabetical order with the other students.
(1) Sequentail search
A sequential search is an iteration through the array that stops at the index where the desired element is found, or, if not found the search stops after
all elements of the list have been iterated through.
This method of searching works for unsorted or sorted arrays, but could take a lot of time, especially on larger arrays.
Since we know that our array of student names is sorted, we could use the much more efficient sorting method Binary search.
Before we use binary search with our students example, let's go through the process of using binary search with integers.
(2) Using Binary search with sorted arrays
Binary searches can only be performed on sorted data.
Lets see how a binary search works by searching for the target value 76 in the array below:
1. Identify the low, middle, and high elements of the array

2. Compare the target value with the middle value: 76 is greater than 56
3. Since the target value is greater than the middle value, it is to the right of the middle. Set the low index to middle +1 then calculate the new middle
index.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
4. Repeat step 2 and compare the target value with the middle value: 76 is less than 81
5. Since the target value is less than the middle value, the is to the left of the middle. Set the high index to middle - 1 then calculate the new middle index.
6. Repeat step 2 and compare the target value with the middle value: 76 is equal to 76
7. The target value has been found at index 7
Note:
When writing a binary search method you will have to decide what to return.
Choose between
Index
Boolean
Value
Entire object
One field of the object

Searching for an element using binarySearch
For the purpose of this course it is important that you understand the principles of the different search methods, but again, as with sort there is a method
already created for us, called bi nar ySear ch( ar r ayName, sear chI t em) .
Below is an implementation thereof in our code.
Remember that you MUST sort the list, is ascending order, before you can use the bi nar ySear ch( ) method.
St r i ng di spl ay=" " ; / / usi ng t hi s t o di spl ay i nf or mat i on
/ / cr eat e an ar r ay myFl ower s wi t h pr edef i ned el ement s.
St r i ng[ ] myFl ower s = {" Rose" , " Sunf l ower " , " Eucal ypt us" , " Dandel i on" , " Vi ol et " , " Li l y" };
i nt l enFl ower s = myFl ower s. l engt h; / / det er mi ne t he l engt h of t he ar r ay myFl ower s

di spl ay = di spl ay+ " \ n" +I nt eger . t oSt r i ng( l enFl ower s) ; / / add t hi s i nf o t o di spl ay
Arrays.sort(myFlowers);
/ / t r aver se t hr ough t he ar r ay
f or ( i nt i =0; i < l enFl ower s; i ++)
{di spl ay = di spl ay + " \ n " + i + " " + myFl ower s[ i ] ; }
int place = Arrays.binarySearch(myFlowers, "Sunflower");
display = display + " \n Search for Sunflower is at index: " + place;
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144345[05/09/2014 16:40:07]
f Di spl ay. set Text ( di spl ay) ; / / di spl ay i nf o on t he scr een
You can download the J ava code from Additional Resources.
Reflection
Reflection
Reflection
Lesson 4: Summary
Now it is your turn ...
In the blogger add a blog entry. Label it Lesson 4. In this blog, enter a short summary for yourself of everything that we've learned. Specifically those
components that you've battled with and how you solved it.
Remember to keep notes and updates in your little black book.
Click here

Das könnte Ihnen auch gefallen