C语言快排函数的实现

来源:互联网 发布:冰与火之歌第八季 知乎 编辑:程序博客网 时间:2024/05/21 17:28

前言:
快排函数之前一直是手写,但在比赛中,可能为了节约时间,就会用到快排函数,直接调用即可,不用很麻烦的敲代码。
简介:

 qsort函数包含在<stdlib.h>头文件里,有四个参数,没有返回值。例 :qsort(s, n, sizeof(s[0]), cmp);1.数组名,即数组所在的首地址。2.排序的个数。3.单个元素的大小。4.。。。。。。

例 :(对int型的排序)

  int cmp(const void * a, const void * b)       {         return *(int *) a - *(int *) b;           }
  A.  对int类型:
 int cmp(const void * a, const void * b)       {         return (*(int *) a - *(int *) b);     
}B. 对double类型/**严格来说,要判断a, b 是否相等,返回0,但double 数不可能相等,只能返回1或-1**/
 int cmp(const void * a, const void * b)    {       return ((*(double *)a - *(double*)b>0) ?1:-1);   }

C .对char排序

int cmp(const void *a, const void * b)   {       return (*(char *) a - *(char *)b);   }

D.对结构体排序
//先在函数里面转换,不要在return里面转。
//注意double返回0的问题

 int cmp(const void * a, const void * b)    {     struct node * aa = (struct node *)a;     struct node * bb =(struct node *)b;     return (((aa->data1)>(bb->data1))?1:-1);      }
E . 字符串数组char * a[2332];
int cmp(const void * a, const void * b)    {         return (strcmp(*(char **)a, *(char **)b));        }

F . 字符串数组char [][];

 int cmp(const void * a, const void * b)   {       return (strcmp((char *)a, (char *)b));   }
C++里面:sort(a, a+10);1.要排序的数组的起始地址。2.结束的地址。3.默认是从小到大(此时可以不写)   也可以从大到小。

A. int 型
例 :

从小到大:

sort(a,a+10);

从大到小:

bool complare(int a,int b){      return a>b;  }sort(a,a+10,complare);//不需要传入参数

B.
Sortt

函数的第三个参数可以用这样的语句告诉程序你所采用的排序

原则

less<数据类型>()//从小到大排序
greater<数据类型>()//从大到小排序
sort函数还可以实现对字符的排序,排序方法大同小异

sort(a,a+10,greater<char>());

C .对于C++结构体的快排;

#include <bits/stdc++.h>using namespace std;struct node{   int a;   int b;}t[23222];bool cmp(struct node  c, struct node d){  if(c.a==d.a)  return c.b>d.b;//b升序  else  return c.a<d.a;//a降序}int main(){   int p;   while(cin>>p)   {       for(int i=0;i<p;i++)       {         cin>>t[i].a>>t[i].b;       }       sort(t, t+p, cmp);       for(int i=0;i<p;i++)       {         cout<<t[i].a<<t[i].b<<endl;       }   }   return 0;}
1 0
原创粉丝点击