467,911 Members | 1,413 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,911 developers. It's quick & easy.

Find Closest value searching an array with linear search

Yep. Newby.
I am asked to find the closest value to user defined value if not right on the mark. I can get it to determin it I have selected one of the generated numbers, but am at a loss how to have it find the closes. here is my code.

Thanks if anyone could assist.
Expand|Select|Wrap|Line Numbers
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using std::cout;
  4. using std::cin;
  5. using std::endl;
  6.  
  7. int linearSearch( const int[],int,int); 
  8.  
  9. int _tmain(int argc, _TCHAR* argv[])
  10. {
  11.        const int max = 100;
  12.        int a[max];
  13.        int searchKey;
  14.  
  15.        for (int i = 0; i < max; i++)
  16.            a[i] = 2*i;
  17.  
  18.  
  19.        cout << "Enter a guess for one of the randomly generated numbers: ";
  20.        cin >> searchKey;
  21.  
  22.        int element = linearSearch ( a, searchKey, max );
  23.  
  24.        if ( element != -1)
  25.            cout << "You found a match in element " << element << endl;
  26.        else
  27.            cout << "Value not found" << endl;
  28.  
  29.     return 0;
  30. }
  31.  int linearSearch(const int array[], int key, int sizeOfArray)
  32.  {
  33.      for ( int j = 0; j < sizeOfArray;j++)
  34.          if ( array[j] == key )
  35.              return j;
  36.  
  37.      return -1;
  38.  }
May 4 '07 #1
  • viewed: 6927
Share:
2 Replies
Ganon11
Expert 2GB
You can have a variable called difference. This will store the difference between the current 'closest element' and the element you are searching for. As you search, compare the current element with the search element. If they are not equal, then see if the difference between the current element and the search element is less than the value in difference - if it is, you have found a new 'closest', if not, then you have not found a new 'closest' At the end of your search, you will have either found the element or found the closest value to the element.
May 4 '07 #2
Hi,

You can use lower_bound or upper bound to find the closest or exact
element.Please note that in order to use these ,the
container has to be sorted.(In your case it is, so you don't have to).

Regards
Prasannaa.
May 4 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Andrew Poulos | last post: by
13 posts views Thread by mike | last post: by
5 posts views Thread by Mike Labosh | last post: by
11 posts views Thread by desktop | last post: by
4 posts views Thread by Thomas Mlynarczyk | last post: by
22 posts views Thread by Steve Richter | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.