Computer >> Máy Tính >  >> Lập trình >> C ++

Cách sử dụng std ::sort để sắp xếp một mảng trong C ++

Trong ngôn ngữ lập trình, sắp xếp là một chức năng cơ bản được áp dụng cho dữ liệu để sắp xếp các dữ liệu này là dữ liệu tăng dần hoặc giảm dần. Trong chương trình C ++, có một hàm std ::sort () để sắp xếp mảng.

sort(start address, end address)

Đây,

Start address => The first address of the element.
Last address => The address of the next contiguous location of the last element of the array.

Mã mẫu

#include <iostream>
#include <algorithm>
using namespace std;
void display(int a[]) {
   for(int i = 0; i < 5; ++i)
   cout << a[i] << " ";
}
int main() {
   int a[5]= {4, 2, 7, 9, 6};
   cout << "\n The array before sorting is : ";
   display(a);
   sort(a, a+5);
   cout << "\n\n The array after sorting is : ";
   display(a);
   return 0;
}

Đầu ra

The array before sorting is : 4 2 7 9 6

The array after sorting is : 2 4 6 7 9