practical of programming 第二章 排序和二分查找

practical of programming 第二章 排序和二分查找
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

using namespace std;
//用于计算数组中元素个数的宏
#define NELEMS(array) (sizeof(array)/sizeof(array[0]))

typedef struct Nameval Namaval;
struct Nameval{
char *name;
int value;
};

Nameval htmlchars[]={
"AElig" , 0x00c6,
"Acute" , 0x00c1,
"Acirc" , 0x00c2,
"zeta" ,  0x03b2,
};

///* lookup: binary search for name in tab; return index */
//int lookup(char *name, Nameval tab[], int ntab){
//    int low, high, mid, cmp;
//    low = 0;
//    high = ntab - 1;
//    while (low<=high){
//        mid = low + ((high-low)/2);
//        cmp = strcmp(name,tab[mid].name);
//        if (cmp<0)
//            high = mid-1;
//        else if (cmp>0)
//            low  = mid + 1;
//        else /* found match */
//            return mid;
//    }
//    return -1; /* no match */
//}

/* swap: interchange v[i] and v[j] */
void swap(int v[],int i, int j){
int temp;
temp = v[i];
v [i] = v[j];
v [j] = temp;
}

/* quicksort: sort v[0]..v[n-1] into increasing order */
void quicksort(int v[], int n){
int i, last;
if (n<=1) /* nothing to do */
return ;
swap (v,0,rand()%n);  /* move pivot elem to v[0] */
last = 0;
for (i = 1; i < n; i++ )  /* partition */
if (v[i] < v[0])
swap (v,++last,i);
swap (v,0,last);   /* restore pivot */
quicksort (v,last);   /* recursively sort */
quicksort (v+last+1,n-last-1);  /* each part */
}
//用C和C++的库函数qsort和bsearch
/* scmp: string compare of *p1 and *p2 用于比较字符串的qsort*/
int scmp(const void *p1, const void *p2){
char *v1, *v2;

v1 = *(char **) p1;
v2 = *(char **) p2;
return strcmp(v1,v2);
}

/* icmp: integer compare of *p1 and *p2 ,用于整数的qsort*/
int icmp(const void *p1, const void *p2){
int v1, v2;
v1 = *(int *)p1;
v2 = *(int *)p2;
if (v1<v2)
return -1;
else if (v1==v2)
return 0;
else
return 1;
}
/* nvcmp: compare two Nameval names for bsearch */
int nvcmp(const void *va, const void *vb){
const Nameval *a, *b;
a = (Nameval *) va;
b = (Nameval *) vb;
return strcmp(a->name, b->name);
}
/* lookup: use bsearch to find name in tab, return index */
int lookup(char *name, Nameval tab[], int ntab){
Nameval key, *np;
key .name = name;
key .value = 0;  /* unused; anything will do */
np = (Nameval *)bsearch(&key,tab,ntab,sizeof(tab[0]),nvcmp);
if (np == NULL)
return -1;
else
return np-tab;
}

int main()
{
int array[10] = {5,9,8,4,2,7,6,1,0,3};
int n = 1;
int half;
double dbuf[5];
printf ("%d %d\n",n++,n++);
printf ("The Html table has %d words\n",NELEMS(htmlchars));
half = lookup("zeta",htmlchars,NELEMS(htmlchars));
printf ("the index of the word is %d. \n",half);
//quicksort(array, 10);
qsort (array,10,sizeof(array[0]),icmp);
for (int i = 0; i<10; i++)
printf ("%3d",array[i]);
return 0;
}

posted @ 2010-02-23 21:18  莫忆往西  阅读(143)  评论(0)    收藏  举报