881642. Sort and reverse
Sort and Reverse Slug: sort-and-reverse--171030 Difficulty: Basic Id: 881642 Topic Tags: STL
Summary
This problem is about sorting a given array in descending order (from largest to smallest) and then reversing it. The key concepts involved are sorting and reversal, which are fundamental algorithms in computer science.
Detailed Explanation
The problem can be solved by first sorting the array in descending order using the std::sort function from the C++ Standard Template Library (STL). This function sorts the elements of a range in ascending or descending order. After sorting the array, we need to reverse it. We can use the std::reverse function from the STL to achieve this.
Here's a step-by-step breakdown of the solution:
- Include the necessary header files:
#include <algorithm>and#include <iostream> - Define an integer array:
int arr[] = {5, 3, 8, 4, 2}; - Sort the array in descending order using
std::sort:std::sort(arr, arr + sizeof(arr) / sizeof(arr[0]), std::greater<int>(); - Reverse the array using
std::reverse:std::reverse(arr, arr + sizeof(arr) / sizeof(arr[0]));
Time complexity: O(n log n), where n is the size of the array. Space complexity: O(1), as we are not using any additional space.
Optimized Solutions
Java
import java.util.Arrays;
public class SortAndReverse {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
Arrays.sort(arr);
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
}
Python
def sort_and_reverse(arr):
arr.sort(reverse=True)
return arr[::-1]
arr = [5, 3, 8, 4, 2]
print(sort_and_reverse(arr))
C++
#include <algorithm>
#include <iostream>
void sortAndReverse(int arr[], int n) {
std::sort(arr, arr + n);
for (int i = 0; i < n / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
sortAndReverse(arr, n);
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
JavaScript
function sortAndReverse(arr) {
arr.sort((a, b) => b - a);
return arr.reverse();
}
let arr = [5, 3, 8, 4, 2];
console.log(sortAndReverse(arr));
Not available