C language USES stdlib.h library function binary search and quick sort of the implementation code
- 2020-04-02 01:53:28
- OfStack
Quick sort:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH(x) sizeof(x)/sizeof(x[0])
void print(char (*arr)[10],int len)
{
int i;
for (i=0;i<len;i++)
{
printf("%s ",arr[i]);
}
printf("n");
}
int main()
{
char arr[][10]={"bac","bca","abc","acb","cba","cab"};
char *key="bca";
char *ptr=NULL;
//Output the contents of the unsorted character array
printf("before qsort :");
print(arr,LENGTH(arr));
qsort((void *)arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);
printf("after qsort :");
print(arr,LENGTH(arr));
ptr=(char *)bsearch(key,arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);
if(ptr)
{
printf("%s is in the arrayn",key);
}
else
{
printf("%s isn't in the arrayn",key);
}
return 0;
}
Binary search:
#include<stdlib.h>
#include<stdio.h>
#define ArrayLen(arr) (sizeof(arr) / sizeof(arr[0]))
int numarray[] = {123, 145, 512, 627, 800, 933};
int numeric (const int *p1, const int *p2)
{
return(*p1 - *p2);
}
int* lookup(int key)
{//The return value is the address to the key
int *itemptr;
// The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at
// compile time
itemptr = (int *)bsearch(&key, numarray, ArrayLen(numarray),
sizeof(int), (int(*)(const void *,const void *))numeric);
return (itemptr);
}
int main(void)
{
int *p = lookup(512);
if(NULL != p)
printf(" To find the key is %d . ", *p);
printf("key The subscript is %dn", (p - numarray));
return 0;
}