运用C++的一些排序

来源:互联网 发布:mac上的开发软件 编辑:程序博客网 时间:2024/06/06 13:09

#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
 int a[10] = {5, 1, 4, 2, 3, 10, 6, 9, 7, 8};
 //max_element()找数组中的最大数,返回指针类型
 printf("the max_element is :%d\n", *max_element(a, a + 10));
 //min_element()找数组中的最小数,返回指针类型
 printf("the min_element is :%d\n", *min_element(a, a + 10));
 //min()找到两个数中的较小数,参数是两个变量,返回元素类型
 int x = 10, y = 20;
 printf("the little element is :%d\n", min(x, y));
 //max()找到两个数中的较大数,参数是两个变量,返回元素类型
 printf("the bigger element is :%d\n", max(x, y));
 printf("\n");
 system("pause");
 return 0;
}

 

另附sort函数排序法--

sort函数排序
需要注意的要点:
1.头文件有两行是C++的写法,所以文件要加后缀为.cpp,那个没有.h!
2.sort默认是升序排法,sort括号内的参数为(数组首元素地址,尾元素下一位地址)。
  并且区间是左闭右开[ )的!
*/

 

#include <stdio.h>
//#include <stdlib.h>
#include <algorithm>  //这两行(+下)是C++的头文件写法,固定的。
using namespace std;

int main()
{
 int a[5] = {5, 1, 4, 2, 3}; //sort的参数是(数组首元素地址,尾元素下一位地址),默认是升序
 sort(a, a + 5);
 for(int i = 0; i < 5; ++i)
  printf("%d ", a[i]);
 printf("\n");
 system("pause");
 return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int main()
{
    int a[3],i;
    for(i=0;i<3;i++)
    {
      scanf("%d",&a[i]);
    }
    sort(a,a+3);
    for(i=0;i<3;i++)
    {
     if(i==0) printf("%d",a[i]);
     else printf(" %d",a[i]);
    }
    printf("\n");
    system("pause");
    return 0;
}

 

0 0
原创粉丝点击