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?

Recommended Answers

All 4 Replies

>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).

/**
 * 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));
    }
 }

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

let me try dis one..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.