Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Last active June 1, 2017 15:56
Show Gist options
  • Save rupalbarman/0761ec3c9e3992b8e61eb8840289e0a9 to your computer and use it in GitHub Desktop.
Save rupalbarman/0761ec3c9e3992b8e61eb8840289e0a9 to your computer and use it in GitHub Desktop.
binary search and qsort in c++ (bsearch, qsort)
#include <iostream>
#include <string.h>
using namespace std;
int compare(const void *a, const void *b){
return (*(int *)a- *(int*)b);
}
int str_compare(const void *a, const void *b) {
return strcmp((char*)a, (char*)b);
}
void sorter() {
int a[]= {1,-2,-13,4,5,6,7};
qsort(a, 7, sizeof(int), compare);
for(int c: a){
cout<<c<<" ";
}
}
void searcher() {
int *key;
int p= 11;
int a[]= {1,2,3,4,5,6,7};
key= (int*)bsearch(&p, a, 7, sizeof(int), compare); //returns void*
if (key== NULL)
cout<<p<<" not found";
else
cout<<*key<<" found";
cout<<endl;
}
void searcher_string() {
char *key;
char p[]= "hello";
char a[][6]= {"hell", "hola", "hello", "bello" };
qsort(a, 4, 6, str_compare);
cout<<a[0]<<endl;
key= (char*) bsearch(p, a, 4, 6, str_compare); //returns void*
if (key== NULL)
cout<<p<<" not found";
else
cout<<key<<" found";
cout<<endl;
}
int main() {
//searcher();
searcher_string();
//sorter();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment