using System;
public class LinearArray
{
private int[] data;
private static Random generator = new Random();
public LinearArray( int size )
{
data = new int[ size ]; // create space for array
for ( int i = 0; i < size; i++ )
data[ i ] = generator.Next( 10, 100 );
}
public int LinearSearch( int searchKey )
{
for ( int index = 0; index < data.Length; index++ )
if ( data[ index ] == searchKey )
return index; // return index of integer
return -1; // integer was not found
}
public override string ToString()
{
string temporary = "";
foreach ( int element in data )
temporary += element + " ";
temporary += "\n";
return temporary;
}
}
using System;
public class LinearSearchTest
{
public static void Main( string[] args )
{
int searchInt; // search key
int position; // location of search key in array
LinearArray searchArray = new LinearArray( 10 );
Console.WriteLine( searchArray ); // print array
Console.Write( "Please enter an integer value (-1 to quit): " );
searchInt = Convert.ToInt32( Console.ReadLine() );
while ( searchInt != -1 )
{
position = searchArray.LinearSearch( searchInt );
if ( position != -1 ) // integer was not found
Console.WriteLine(
"The integer {0} was found in position {1}.\n",
searchInt, position );
else // integer was found
Console.WriteLine( "The integer {0} was not found.\n",
searchInt );
Console.Write( "Please enter an integer value (-1 to quit): " );
searchInt = Convert.ToInt32( Console.ReadLine() );
} // end while
}
}
No comments:
Post a Comment