Write a program to sort the array in descending order
Example 1:
Input :arr[]={3,1,4,12,6,9,2}
Output: 12 9 6 4 3 2 1
Approach:
Java
import java.util.Arrays;public class SortArrayInDesc {public static void main(String[] args) {int arr[] = { 3, 1, 4, 12, 6, 9,2 };sortingDesc(arr, arr.length);Arrays.stream(arr).forEach(e -> System.out.print(e + " "));}static void sortingDesc(int[] arr, int N) {for (int i = 0; i < N; i++) {int min = i;for (int j = i + 1; j < N; j++) {// descending orderif (arr[min] < arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}}}//Time Complexity: O(n^2)//Space Complexity: O(1)
C++
#include <bits/stdc++.h>using namespace std;//function to sort the array//in descending ordervoid sortingDesc(int arr[], int N){for (int i = 0; i < N; i++){int min = i;for (int j = i + 1; j < N; j++) {// descending orderif (arr[min] < arr[j]) {min = j;}}// Swapping elementint tmp = arr[min];arr[min] = arr[i];arr[i] = tmp;}}int main(){int arr[] = { 3, 1, 4, 12, 6, 9,2 };int n=sizeof(arr)/sizeof(arr[0]);sortingDesc(arr, n);for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity: O(n^2)//Space Complexity: O(1)
No comments:
Post a Comment