C++标准模板库(STL)中如何使用排序算法?

2021年4月1日15:10:03 发表评论 715 次浏览

排序

是应用于数据的最基本功能之一。这意味着以特定的方式排列数据, 可以增加或减少。 C ++ STL中有一个内置函数, 名称为sort()。

此函数在内部使用IntroSort。更详细地讲, 它是使用QuickSort, HeapSort和InsertionSort的混合实现的。默认情况下, 它使用QuickSort, 但是如果QuickSort进行不公平的分区并且花费的时间超过N * logN, 它将切换到HeapSort, 并且当数组大小变得非常小时, 它切换到InsertionSort。

排序的原型是:

sort(startaddress, endaddress)

startaddress: the address of the first 
              element of the array
endaddress: the address of the next 
            contiguous location of the 
            last element of the array.
So actually sort() sorts in the 
range of [startaddress, endaddress)

CPP

// C++ progrma to sort an array
#include <algorithm>
#include <iostream>
 
using namespace std;
 
void show( int a[], int array_size)
{
     for ( int i = 0; i < array_size; ++i)
         cout << a[i] << " " ;
}
 
// Driver code
int main()
{
     int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
   
     // size of the array
     int asize = sizeof (a) / sizeof (a[0]);
     cout << "The array before sorting is : \n" ;
   
     // print the array
     show(a, asize);
 
       // sort the array
     sort(a, a + asize);
 
     cout << "\n\nThe array after sorting is :\n" ;
   
     // print the array after sorting
     show(a, asize);
 
     return 0;
}

输出如下

The array before sorting is : 
1 5 8 9 6 7 3 4 2 0 

The array after sorting is :
0 1 2 3 4 5 6 7 8 9

参考std::sort()更多细节。

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C++ STL通过激烈的问题解决过程来训练和掌握这些概念。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: