首页 > 其他 > 详细

sort 与 qsort

时间:2014-04-11 00:08:09      阅读:521      评论:0      收藏:0      [点我收藏+]

很长一段时间搞不明白 sort 和 qsort 的区别,平时在写程序时习惯了使用 sort ,因为它用起来比 qsort 要简单的多 , 这里详细介绍一下 sort 与 qsort :

  给出一个数组 a[10] = {3 , 2 , 4 , 6 , 7 , 5} ;

  若要实现从小到大输出;

  sort 实现如下:

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
#include<algorithm>
using namespace std ;
int a[10] = {3 , 2 , 4 , 6 , 7 , 5} ;
int main() {
    sort(a,a+6) ;
    for(int i = 0 ; i < 6 ; i++)
        cout << a[i] << " " ;
    cout << endl ;
    return 0 ;
}

 从大到小代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<algorithm>
using namespace std ;
int a[10] = {3 , 2 , 4 , 6 , 7 , 5} ;
 
int cmp(int a , int b ) {
    return a > b ;
}
 
int main() {
    sort(a,a+6,cmp) ;
    for(int i = 0 ; i < 6 ; i++)
        cout << a[i] << " " ;
    cout << endl ;
    return 0 ;
}

 qsort 实现如下:

  从大到小 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<algorithm>
using namespace std ;
int a[10] = {3 , 2 , 4 , 6 , 7 , 5} ;
 
int cmp(const void *a , const void *b ) {
    int *_a = (int *)a ;  // a 强制转化为指针
    int *_b = (int *)b ;  // b 强制转化为指针
    return *_a > *_b ;   // 和 sort完全相反
}
 
int main() {
    qsort(a,6,sizeof(int),cmp) ;
    for(int i = 0 ; i < 6 ; i++)
        cout << a[i] << " " ;
    cout << endl ;
    return 0 ;
}

 

sort 与 qsort,布布扣,bubuko.com

sort 与 qsort

原文:http://www.cnblogs.com/scottding/p/3656507.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!