Question

Assume that you are given an unsorted array that contains 100 items, and you have been...

Assume that you are given an unsorted array that contains 100 items, and you have been asked to write/propose an efficient searching algorithm. Which algorithm would you choose and why? What are the possible trad-offs of the selected algorithm if the array size is increased (e.g., 9000 items)?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Sequential Search

If you want to find the position in an unsorted array of n integers that stores a particular value, we cannot really do better than simply looking through the array from the beginning and move toward the end until you find what you are looking for. This algorithm is called sequential search.

Here is a simple implementation for sequential search.

JAVA CODE :

// Return the position of an element in array A with value K.
// If K is not in A, return A.length.
static int sequential(int[] A, int K) {
  for (int i=0; i<A.length; i++) // For each element
    if (A[i] == K)               // if we found it
       return i;                 //   return this position
  return A.length;               // Otherwise, return the array length
}

C++ CODE :

// Find the position in A that holds value K, if any does
int sequential(int A[], int size, int K) {
  for (int i=1; i<size; i++)     // For each element
    if (A[i] == K)               // if we found it
       return i;                 //   return this position
  return size;                   // Otherwise, return the array length
}

In the case of sequential search, it is easy to see that if the value is in position i of the array, then sequential search will look at i values to find it. If the value is not in the array at all, then we must look at n values if the array holds n values. This would be called the worst case for sequential search.

Since the amount of work is proportional to n, we say that the worst case for sequential search has linear cost. For this reason, the sequential search algorithm is sometimes called linear search.

It will work great with both type of data i.e. 100 items as well as 9000 items.

Add a comment
Know the answer?
Add Answer to:
Assume that you are given an unsorted array that contains 100 items, and you have been...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT