Solved

Search an array

Posted on 1997-12-06
3
204 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
3 Comments
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
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
Comment Utility
Uhmm... Why not use bsearch() from the standard run-time C library?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

772 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now