4/27: Sorting and Searching Arrays

Download Report

Transcript 4/27: Sorting and Searching Arrays

4/10: Sorting Arrays
• Look at PassArray.java
• Sorting arrays: the bubble sort method
PassArray.java -- pt. 1
//Fig 7.10: PassArray.java
//Passing arrays and individual elements to methods
import java.awt.Container;
import javax.swing.*;
public class PassArray extends JApplet {
public void init()
{
JTextArea outputArea = new JTextArea();
Container container = getContentPane();
container.add( outputArea );
PassArray.java -- pt. 2
int array[] = { 1, 2, 3, 4, 5 };
String output = "Effects of passing entire " +
"array call-by-reference:\n" +
"The values of the original array are:\n";
for ( int count = 0; count < array.length ; count++ )
output += " " + a[ i ];
modifyArray ( array ); //passing the whole array
output+="\n\nValues of the modified array are:\n";
PassArray.java -- pt. 3
for ( int count = 0; count < array.length ; count++ )
output += " " + array[ i ];
output += "\n\nEffects of passing array " +
"element call-by-value:\n" +
"array[3] before modifyElement: " + a[ 3 ];
modifyElement ( array [ 3 ] );
}
output += "\narray[3] after modifyElement: “+ a[3];
outputArea.setText ( output );
PassArray.java -- pt. 4
public void modifyArray ( int array2[] )
{
for ( int j = 0 ; j < array2.length; j++ )
array2 [ j ] *= 2;
}
}
public void modifyElement ( int element )
{
element *= 2;
}
Sorting Arrays using Bubble Sort
• Reorganizing an array in some
order (low to high, etc.)
• Bubble Sort compares two
values, switches them in the
array positions if appropriate,
and checks the next two values.
3619
3619
3169
3169
Sorting Arrays using Bubble Sort
• In this case, 3 & 6 are compared,
and NOT switched.
• Then, 6 & 1 are compared, then
switched.
• Then 6 & 9 are compared and
NOT switched.
• This is ONLY ONE PASS
through the array.
3619
3619
3169
3169
Sorting Arrays using Bubble Sort
• Core of sorting: an if structure.
• This is nested inside a for loop
to look at each pair of values in
the array.
• This loop in nested inside
another loop to make multiple
passes through the array.
• Look at SortThem & its source
code.
3619
3619
3169
3169
Program of the Day
• pg. 333 BubbleSort.java
• Once you get it to work, figure out how it works.
• Next time: searching arrays using linear search &
binary search.