在 C++ 中使用 std::sort 來對陣列進行排序
在程式語言中,排序是一種基本函式,用於對資料進行排序,將這些資料排列為升序或降序資料。在 C++ 程式中,有一個函式 std::sort() 用於對陣列進行排序。
sort(start address, end address)
在此處,
Start address => The first address of the element. Last address => The address of the next contiguous location of the last element of the array.
示例程式碼
#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; }
輸出
The array before sorting is : 4 2 7 9 6 The array after sorting is : 2 4 6 7 9
廣告