Quick sort:
Copy Code code as follows:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH (x) sizeof (x)/sizeof (x[0])
/** Output Array element
*\param arr: pointer to array
*\param len: Number of array elements
*/
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"}; /* Define a two-dimensional character array * *
Char *key= "BCA";/* the string to find * *
Char *ptr=null; /* Character Pointer/*
The contents of an array of characters when the output is not sorted
printf ("Before qsort:");
Print (Arr,length (arr));
/* Use Qsort to sort the array of characters * *
Qsort (void *) Arr,length (arr), sizeof (arr[0)), (Int (*) (const void *,const void *)) strcmp);
/* The contents of the character array after the output is sorted * *
printf ("After qsort:");
Print (Arr,length (arr));
/* Use a binary lookup to find the specified character * *
Ptr= (char *) bsearch (Key,arr,length (arr), sizeof (arr[0)), (Int (*) (const void *,const void *)) strcmp);
if (PTR)
{
* * Find * *
printf ("%s is in the array\n", key);
}
Else/* didn't find it.
{
printf ("%s isn ' t in the" array\n ", key);
}
return 0;
}
Two-point search:
Copy Code code as follows:
#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 of 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 ("Found key is%d,", *p);
printf ("Key's subscript is%d\n", (P-numarray));
return 0;
}