zoukankan      html  css  js  c++  java
  • sort 与 qsort

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

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

      若要实现从小到大输出;

      sort 实现如下:

    #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 ;
    }
    

     从大到小代码如下:

    #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 实现如下:

      从大到小 :

    #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 ;
    }
    
  • 相关阅读:
    微服务简介
    Apache httpd.conf
    搭建PHP开发环境
    搭建Apache开发环境
    Swift 项目编译优化(一)
    用Flutter 写一个简单页面
    Sign In With Apple(一)(转)
    Xcode DeviceSupport
    MQTT初始篇笔记整理
    UITableView使用过程中可能遇到的问题
  • 原文地址:https://www.cnblogs.com/NYNU-ACM/p/4237455.html
Copyright © 2011-2022 走看看