C++ array sort method
#include <iostream>
#include <algorithm>
int main() {
const int size = 5;
int arr[size] = {4, 2, 7, 1, 5};
std::cout << "Original array: ";
for (int i = 0; i < size; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
std::sort(arr, arr + size);
std::cout << "Sorted array: ";
for (int i = 0; i < size; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}
Include necessary headers: Include the
<iostream>
and<algorithm>
headers, which provide input/output stream functionality and algorithms likestd::sort
, respectively.Define main function: Start the
main
function, the entry point of the program.Initialize array: Declare a constant integer
size
and an integer arrayarr
of that size, with initial values.Display original array: Use a
for
loop to iterate through the elements of the array and display them on the console.Sort the array: Use
std::sort
to sort the array in ascending order. Pass the beginning and end iterators of the array as arguments.Display sorted array: Use a
for
loop again to iterate through the sorted array and display its elements on the console.Return 0: The
main
function returns 0 to indicate successful execution.