702910. Sort The Array

Basic

Sort The Array

Summary

This problem is about sorting an array in a specific order. Given an array of integers, sort it in ascending or descending order based on user input. This problem involves basic algorithms and data structures.

Detailed Explanation

The goal is to write a function that takes an array of integers as input and returns the sorted array. The catch here is that the sorting should be done based on a specific direction (either ascending or descending) which will be provided along with the input array.

Here's the step-by-step breakdown of the solution:

  1. First, we need to determine the direction of sorting (ascending or descending). This information will be provided as an additional input.
  2. Next, we can use a standard sorting algorithm like Bubble Sort or Selection Sort to sort the array. The choice of algorithm depends on the specific requirements and constraints.

Here's a step-by-step breakdown of the Bubble Sort algorithm:

for i in range(len(arr)-1):
    for j in range(0, len(arr)-i-1):
        if arr[j] > arr[j+1]:
            arr[j], arr[j+1] = arr[j+1], arr[j]

In this code, we iterate over the array and compare adjacent elements. If they are out of order, we swap them. This process continues until no more swaps are needed, indicating that the array is sorted.

Time Complexity: O(n^2) where n is the number of elements in the array. Space Complexity: O(1), as we only use a constant amount of space to store temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] sortArray(int[] arr, boolean isAscending) {
    if (isAscending) {
        Arrays.sort(arr);
    } else {
        Arrays.sort(arr);
        reverseArray(arr);
    }
    return arr;
}

private void reverseArray(int[] arr) {
    for (int i = 0; i < arr.length / 2; i++) {
        int temp = arr[i];
        arr[i] = arr[arr.length - i - 1];
        arr[arr.length - i - 1] = temp;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.