Skip to main content

Sort The Array

Problem​

Given a random set of numbers, Print them in ascending sorted order.

Examples:​

Example 1:

Input:
n = 4
arr[] = {1, 5, 3, 2}
Output: {1, 2, 3, 5}
Explanation: After sorting array will
be like {1, 2, 3, 5}.

Example 2:

Input:
n = 2
arr[] = {3, 1}
Output: {1, 3}
Explanation: After sorting array will
be like {1, 3}.

Your task:​

You don't need to read input or print anything. Your task is to complete the function sortArr() which takes the list of integers and the size n as inputs and returns the modified list.

  • Expected Time Complexity: O(nβˆ—logn)O(n * log n)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1≀n,arr[i]≀1051 ≀ n, arr[i] ≀ 10^5

Solution​

Python​

def sortArr(self, arr, n): 
arr.sort()
return arr

Java​

int[] sortArr(int[] arr, int n) { 
Arrays.sort(arr);
return arr;
}

C++​

vector<int> sortArr(vector<int>arr, int n){
sort(arr.begin(), arr.end());
return arr;
}

C​

int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}

void sortArr(int arr[], int n) {
qsort(arr, n, sizeof(int), compare);
}
  • Time Complexity: O(nβˆ—logn)O(n * log n)
  • Auxiliary Space: O(1)O(1)