数组查找

来源:互联网 发布:知画的孩子是谁的 编辑:程序博客网 时间:2024/06/05 15:34

查找:找出数组中特定元素的过程。


线性查找

利用查找关键值与每一个数组元素进行比较。

由于元素的排列是随机的,其概率是均匀分布的,因此程序必须同数组的一半元素进行比较。

线性查找适用于小数组或未排序的数组。

example:

// Linear search programimport 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 variablespublic 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 methodpublic int linearSearch( int n ){for ( int i = 0; i < array.length; i++) {if ( array[ i ] == n )return i;}return -1;}// process to the actionpublic 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." );elseresultText.setText( "Found value in element " + result );}return true;}}

结果如图

                                


二分查找

适用于有序数组

找到中间的数组元素并将其与查找关键值相比较。如果相等,则返回下标。否则,就变为在数组的一半元素中查找。以此类推,直到找到关键值。

若数组中有2^n个元素,则最多只需查找n次。

example:

// Binary search programimport 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 componentspublic 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 definitionpublic 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 actionpublic 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." );elseresultText.setText( "Found value in element " + result );}return true;}}





原创粉丝点击