Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Search an array

Posted on 1997-12-06
3
Medium Priority
?
211 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 100 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

Independent Software Vendors: 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

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…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

715 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