Presentation is loading. Please wait.

Presentation is loading. Please wait.

4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search.

Similar presentations


Presentation on theme: "4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search."— Presentation transcript:

1 4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search

2 BubbleSort.java: 1 of 4 import java.awt.*; import javax.swing.*; public class BubbleSort extends JApplet { public void init () { JTextArea outputArea = new JTextArea(); Container container = getContentPane(); container.add ( outputArea ); int array[]= {2,6,4,8,10,12,89,68,45,37}; String output = “Items in orig. order\n";

3 BubbleSort.java : 2 of 4 for ( int c = 0; c < array.length; c++ ) output += " " + array[ c ]; bubbleSort( array ); // sort array output += "\n\nItems in ascend. order\n"; for ( int c = 0; c < array.length; c++ ) output += " " + array[ c ]; outputArea.setText( output ); } //end init method

4 BubbleSort.java : 3 of 4 public void bubbleSort( int a2[] ) { for ( int pass=1; pass<a2.length; pass++ ) { for ( int el=0; el<a2.length-1; el++ ) { if ( a2[ el ] > a2[ el + 1 ] ) swap( a2, el, el + 1 ); } // end inner loop } // end outer loop to control passes } // end method bubbleSort

5 BubbleSort.java : 4 of 4 public void swap(int a3[],int first,int second) { int hold; // temp holding area for swap hold = a3[ first ]; a3[ first ] = a3[ second ]; a3[ second ] = hold; } } // end class BubbleSort

6 Searching Arrays: Linear Search How do you find a particular element value in an array? One way: a linear search. The core structure: an if statement in a for loop. The for loop gives movement through the array The if structure looks for a matching value in the elements.

7 Searching Arrays: Linear Search The for loop gives movement through the array The if structure looks for a matching value in the elements. for ( int n = 0 ; n < array.length ; n++ ) { if ( array [ n ] == key ) return n ; }

8 Searching Arrays: Binary Search Go to the middle of the array. See if the number you are looking for is higher or lower, and go to the middle of that side. Repeat until found. Note that the array must already be sorted!

9 Searching Arrays: Linear vs. Binary A linear search works well for smaller arrays, and is simpler to understand and troubleshoot. A binary search is better for a large array. It is more efficient in its searching.

10 Program of the Day: BinarySearch pg. 339 BinarySearch.java Once you get it to work, figure out how it works. Next time: review searching and learn about multiple-subscripted arrays.


Download ppt "4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search."

Similar presentations


Ads by Google