class ImprovedSequentialSearch
{
public static int seqSearch (int[] list, int item)
{
int location = -1;
boolean found = false;
for (int i = 0 ; i < list.length && !found ; i++)
if (list [i] == item)
{
location = i;
found = true;
if (i != 0)
{
int temp = list [i - 1];
list [i - 1] = list [i];
list [i] = temp;
}
}
return location;
}
public static void printList (int[] list)
{
for (int i = 0 ; i < list.length ; i++)
System.out.print (list [i] + " ");
System.out.println ();
}
public static void main (String[] args)
{
System.out.println ("How long will the list be?");
int length = In.getInt ();
int[] list = new int [length];
for (int i = 0 ; i < length ; i++)
{
System.out.println ("Please enter " + (length - i) + " more integer(s).");
list [i] = In.getInt ();
}
System.out.print ("Initial List: ");
printList (list);
System.out.println ("Please enter a number to find.");
int input = In.getInt ();
int result = 0;
while (input != 0)
{
result = seqSearch (list, input);
if (result == -1)
System.out.println ("Item not found");
else
{
System.out.println ("Item found at position " + (result + 1));
printList (list);
}
System.out.println ("Please enter a number to find.");
input = In.getInt ();
}
}
}
|