字符串排序
在主函数中输入10个等长的字符串。用另一函数对它们排序。然后在主函数输出这10个已排好序的字符串。
思路: 定义一个字符串数组(10个字符串元素),使指针p指向第一个字符串数组,使p+1。
使用strcmp函数进行比较后,按小到大的顺序进行排序。
#include <iostream>
using namespace std;
int main()
{
void sort(char *,int);
string str[10]={"name","what","okay","when","abut","damn","haha","jack","rose","then"}; // 定义10个等长的字符串
// char *p=str; 定义错误?
string *p=str;
int i=0;
sort(p,10);
cout<<"the str of sort:"<<endl;
for(;p<(str+10);p++)
cout<<*(p+i)<<endl;
return 0;
}
void sort(char *p1,int n)
{
int i;
char temp;
for(;p1<(p1+n);p1++)
if(*(p1+i)>*(p1+i+1))
temp=*(p1+i);
*(p1+i)=*(p1+i+1);
*(p1+i+1)=temp;
}
调试有好几处错误 本人菜鸟刚接触指针这一块 看了半天实在是搞不出来 求帮助啊!
[解决办法]
#include <stdio.h>#include <string.h>#include <stdlib.h>int cmp(const void *a, const void *b){ return strcmp((char *)a, (char *)b);}int main(){ char* str[10]={"name","what","okay", "when", "abut", "damn", "haha","jack","rose","then"}; // 定义10个等长的字符串 int i; qsort(str, 10, sizeof(char)*4, cmp); for(i = 0;i<10; i++) printf("%s ", str[i]); printf("\n"); return 0;}
[解决办法]
qsort函数是ANSI C标准中提供的,其声明在stdlib.h文件中,是根据二分发写的,其时间复杂度为n*log(n),其结构为:
void qsort(void *base,size_t nelem,size_t width,int (*Comp)(const void *,const void *));
其中:
*base 为要排序的数组
nelem 为要排序的数组的长度
width 为数组元素的大小(一字节为单位)
默认是从小到大排序的!
(* Comp)(const void *p1,const void *p2) 为判断大小函数的指针,这个函数需要自己定义,如果p1>p2,函数返回-1;a<b,函数返回1;a==b函数返回0
排序方法有很多种:选择排序,冒泡排序,归并排序,快速排序等。
看名字都知道快速排序是目前公认的一种比较好的排序算法(我没听说速度比这快的了,特殊场合例外),比选择排序,冒泡排序都要快。这是因为他速度很快,所以系统也在库里实现这个算法,便于我们的使用。
这就是qsort。