查找:找出数组中特定元素的过程。
线性查找
利用查找关键值与每一个数组元素进行比较。
由于元素的排列是随机的,其概率是均匀分布的,因此程序必须同数组的一半元素进行比较。
线性查找适用于小数组或未排序的数组。
example:
// Linear search program
import java.applet.Applet;
import java.awt.Event;
import java.awt.Label;
import java.awt.TextField;
public class LinearSearch extends Applet{
int array[ ] = { 1, 4, 45, 87, 2, 98, 43, 37, 87, 54,
12, 77, 11, 18, 28, 33, 5, 51, 29, 73,
21, 71, 46, 22, 47, 49, 64, 55, 19, 6 };
int key, result;
Label enterLabel, resultLabel;
TextField enterText, resultText;
// setup the graphical user interface components
// and initialize the variables
public void init()
{
enterLabel = new Label( "Enter the search key ( integer )" );
resultLabel = new Label( "Result" );
enterText = new TextField( 10 );
resultText = new TextField( 30 );
resultText.setEditable( false );
add( enterLabel );
add( enterText );
add( resultLabel );
add( resultText );
}
// linearSearch method
public int linearSearch( int n )
{
for ( int i = 0; i < array.length; i++) {
if ( array[ i ] == n )
return i;
}
return -1;
}
// process to the action
public boolean action( Event e, Object o )
{
if ( e.target == enterText ) {
key = Integer.parseInt( enterText.getText() );
result = linearSearch( key );
if ( result == -1 )
resultText.setText( "Value not found." );
else
resultText.setText( "Found value in element " + result );
}
return true;
}
}
结果如图
二分查找
适用于有序数组
找到中间的数组元素并将其与查找关键值相比较。如果相等,则返回下标。否则,就变为在数组的一半元素中查找。以此类推,直到找到关键值。
若数组中有2^n个元素,则最多只需查找n次。
example:
// Binary search program
import java.applet.Applet;
import java.awt.Event;
import java.awt.Label;
import java.awt.TextField;
public class BinarySearch extends Applet{
int [] array, b;
int key, result;
Label enterLabel, resultLabel;
TextField enterText, resultText;
// setup the graphical user interface components
public void init()
{
array = new int[ 100 ];
for ( int i = 0; i < array.length; i++ )
array[ i ] = 2 * i;
enterLabel = new Label( "Enter the search key value" );
resultLabel = new Label( "Result" );
enterText = new TextField( 10 );
resultText = new TextField( 30 );
resultText.setEditable( false );
add( enterLabel );
add( enterText );
add( resultLabel );
add( resultText );
}
// binarySearch method definition
public int binarySearch( int a[], int key, int high, int low )
{
while ( low <= high ) {
int mid = ( high + low ) / 2;
if ( a[ mid ] == key )
return mid;
else if ( key < a[ mid ] )
return binarySearch( a, key, mid - 1, low );
else if ( key > a[ mid ] )
return binarySearch( a, key, high, mid + 1 );
}
return -1;
}
// process to action
public boolean action( Event e, Object o )
{
if ( e.target == enterText ) {
key = Integer.parseInt( enterText.getText() );
result = binarySearch( array, key, array.length, 0 );
if ( result == -1 )
resultText.setText( "Value not found." );
else
resultText.setText( "Found value in element " + result );
}
return true;
}
}