Time Limit: 2s Memory Limit: 192MB Submissions: 14674 Solved: 9055
Problem Description
Sort four integers in ascending order.
Input Format
Four integers
Output Format
Output these four numbers in ascending order
Sample Input
5 3 4 2
Sample Output
2 3 4 5
Code
#include <iostream>
#include <algorithm> // for sort function
using namespace std;
int main() {
int arr[4];
// Input four integers
for (int i = 0; i < 4; i++) {
cin >> arr[i];
}
// Sort using sort function (default ascending order)
sort(arr, arr + 4);
// Output sorted result
for (int i = 0; i < 4; i++) {
cout << arr[i];
if (i < 3) cout << " "; // No space after the last number
}
cout << endl;
return 0;
}
Output Result
Code Explanation:(1) Header Files: <iostream> for input and output <algorithm> includes the sort function(2) Array Storage: Use an integer array arr of size 4 to store the four input numbers(3) Input Handling: Use a for loop to read 4 integers into the array(4) Sorting: Use sort(arr, arr + 4) to sort the array in ascending order The sort function is an efficient sorting algorithm in the C++ standard library (usually quicksort)(5) Output: Use a for loop to output the sorted array elements Add spaces between numbers, no space after the last numberAnother Implementation Method (Manual Sorting):
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
// Use bubble sort idea for multiple comparisons and swaps
if (a > b) swap(a, b);
if (a > c) swap(a, c);
if (a > d) swap(a, d);
if (b > c) swap(b, c);
if (b > d) swap(b, d);
if (c > d) swap(c, d);
cout << a << " " << b << " " << c << " " << d << endl;
return 0;
}
Extended Knowledge:sort function: Is a sorting algorithm in the C++ Standard Template Library (STL) Time complexity is O(n log n) Default is ascending order; for descending order, use: sort(arr, arr+4, greater<int>())swap function: Used to swap the values of two variables Is a C++ standard library function, defined in <algorithm> or <utility>Recommendation:The first method (using sort) is more concise and readable, suitable for beginnersThe second method demonstrates the basic principles of sorting, helping to understand algorithm conceptsIn practical programming, the first method is recommended for higher efficiency and lower error rates
C++ Basic Tutorial Collection
C++ Basic Materials
1. C++ Output
2. C++ Variables
3. C++ Input
4. C++ Expressions
5. IF Statements
6. IF Applications
7. WHILE Loop Statements
8. FOR Loop Statements
9. Arrays
10. One-Dimensional Arrays
11. Two-Dimensional Arrays
12. C++ Functions
13. C++ File Operations – Writing Files
If you find it useful, please click on me



