954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Sequential search in java

hi.i've written a program that loads #'s into an array and sorts them.The end user then inputs a number and the program is supposed to perform a sequential search for the input number and tell wether it was found or not found.I'm hoping someone canhelp me with my sequential search.binary gave me enough trouble.any idea?

josirucu
Newbie Poster
2 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

>binary gave me enough trouble.
Binary search is leaps and bounds more complex than sequential search. Start at the beginning, and go to the end. If you find a match, stop. What's so hard about that? You probably solved the first half of the problem when you printed the sorted array (ie. start at the beginning and go to the end).

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 
/**
 * Requires j2se 5.0 (version 1.5).  This uses class Scanner, static import,
 * and some methods of class Arrays.
 */

import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Math.*;

public class Prog3c_1
{
    public static void main(String... args)
    {
        Scanner sc = new Scanner(System.in);

        int j, k, number, size;
        boolean found = false;

        System.out.print("Enter the array size: ");
        size = sc.nextInt();

        int[] intArray = new int[size];

        for (j=0; j<size; j++)
            intArray[j] = (int) (random()*100);

        System.out.println("A " + size + " element int array of random "
                         + "ints between 0 and 99 has been loaded.");
        System.out.print("Guess one of the numbers: ");
        number = sc.nextInt();

        k=0;
        while (!found && k<size)
        if (intArray[k]==number)
            found=true;
        else
            k +=1;

        System.out.println();
        if (found)
            System.out.println("Found in position " + k);
        else
            System.out.println("The number is not found");

        System.out.println("\nThe random array for verification is:\n");
        System.out.println(Arrays.toString(intArray));
    }
 }
paradox814
Posting Whiz
351 posts since Oct 2004
Reputation Points: 13
Solved Threads: 4
 

There's always some goofball who encourages lazy students by doing their homework for them.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

let me try dis one..

foxpro21
Newbie Poster
1 post since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You