2019独角兽企业重金招聘Python工程师标准>>>
//对字符串排序
#include<iostream>
#include<cstdlib>
#include<string.h>
#define N 8
using namespace std;
int compare(const void *a,const void *b);
int main(void)
{int i;char s[8][10]= {"January","February","March","April","May","June","July","September"};qsort(s,8,sizeof(char)*10,compare);for(i=0; i<8; i++)cout<<s[i]<<endl;return 0;
}
int compare(const void *a,const void *b)
{if(strlen((char *)a)!=strlen((char *)b))return strlen((char *)a)-strlen((char*)b);return (strcmp((char *)a,(char *)b));
}
//===============================================================
//对正型数组从小到大排序
#include<iostream>
#include<cstdlib>
#include<string.h>
using namespace std;
int compare(const void *a,const void *b);
int main(void)
{int i;int s[10] = {1,3,2,4,6,5,7,8,9,0};qsort(s,10,sizeof(int),compare);for(i=0; i<10; i++)cout<<s[i]<<endl;return 0;
}
int compare(const void *a,const void *b)
{if(*(int *)a != *(int *)b)return *(int *)a - *(int *)b;return 0;
}
//================================================================
//使用查找
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int compare(const void *a,const void *b);
int main(void)
{int i;int s[10] = {1,3,2,4,6,5,7,8,9,0};//使用排序qsort(s,10,sizeof(int),compare);for(i=0; i<10; i++)cout<<s[i]<<endl;//使用二分查找int key = 5;int *p = (int *)bsearch(&key, s, 10, sizeof(int), compare);int pos = p - s;cout<<"bsearch pos = "<<pos<<endl;
/*//线性查找int tot_size = 10;key = 7;p = (int *)lsearch(&key, s, &tot_size, sizeof(int), compare);pos = p - s;cout<<"lsearch pos = "<<pos<<endl;
*/return 0;
}
//比较函数的实现
int compare(const void *a,const void *b)
{if(*(int *)a != *(int *)b)return *(int *)a - *(int *)b;return 0;
}