Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to write an example of O(log n) time complexity in C

1 Answer

0 votes
#include <stdio.h>

// The notation O(log n) represents logarithmic time complexity. 
// The time complexity of an algorithm grows logarithmically with the size n.
 
int binarySearch(int array[], int element, int low, int high) {
    while (low <= high) {
        int n = high - low;
        int mid = low + n / 2;
  
        if (array[mid] == element)
            return mid;
  
        if (array[mid] < element)
            low = mid + 1;
        else
            high = mid - 1;
    }
      
    return -1;
}
  
int main(void) {
    int array[] = {3, 4, 8, 9, 10, 17, 21, 28, 33, 36, 42};
    int number_to_find = 21;
  
    int index = binarySearch(array, number_to_find, 0, sizeof(array)/sizeof(array[0]));
          
    if (index == -1) 
        puts("Not found");
    else
        printf("Found at index: %d", index);
        
    return 0;
}

  
  
/*
run:
  
Found at index: 6
  
*/

 



answered Dec 13, 2024 by avibootz
edited Dec 13, 2024 by avibootz

Related questions

1 answer 198 views
1 answer 193 views
1 answer 194 views
1 answer 192 views
1 answer 199 views
1 answer 109 views
3 answers 190 views
...