Solved

Search an array

Posted on 1997-12-06
3
207 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
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How do I test for current date? 9 103
why debugging a macro i s difficult 10 34
Convert image to byte array 8 202
C dll call freezes 5 102
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
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…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files 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.

809 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