Solved

Search an array

Posted on 1997-12-06
3
210 Views
Last Modified: 2010-04-02
What is the quickest way to seatch an array that is already sorted?  ANd how do I do it?
0
Comment
Question by:mattkr
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 1256534
int min=0;
int max=(sizeof(array)/sizeof(array[0]))-1;
while( min < max ){
       int x = (max+min)/2;
       if( array[x] < target ){
              min = x+1;
       }else if( array[x] > target ){
              max = x-1;
       }else{
              printf("array[%d] = %d\n",x,array[x]);
            max=min=x;
       }
}


0
 
LVL 10

Accepted Solution

by:
rbr earned 50 total points
ID: 1256535
Use binary search.

array is the array in which you want to search. target is the element you want to find.

int a=0;
int b=(sizeof(array)/sizeof(array[0]))-1;
int element;

while (a < b) {
    element = (a+b)/2;
    if (array[element] < target) {
       a=element+1;
    } else {
       if (array[element] > target) {
           b=element-1;
       } else {
           break;
       }
    }
}

if (a<b) {
    printf ("Found at pos.: %d",element);
} else {
    printf ("Not found");
}
0
 
LVL 11

Expert Comment

by:alexo
ID: 1256536
Uhmm... Why not use bsearch() from the standard run-time C library?
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question