# Sort an array after applying the given equation

We have an integer array that is sorted in ascending order. We also have 3 integers A, B and C. We need to apply A*x*x + B*x + C for each element x in the array and sort the modified array.

Example:

`Input : arr[] = {-1, 0, 1, 2, 3, 4}        A = -1, B = 2, C = -1Output : {-9, -4, -4, -1, -1, 0}  Expalnation:Input array is {-1, 0, 1, 2, 3, 4}. Afterapplying the equation A*x*x + B*x + C onevery element x we get, {-4,-1, 0, -1, -4, -9}After sorting, we get {-9, -4, -4, -1, -1, 0}`

Method 1 (Simple) :

1. Apply the given equation to all the elements. O(n)
2. Sort the modified array. O(n log n)

The time complexity of O(n log n)

Algorithm:

1.    Initialize an array arr of size n with given elements.
2.    Initialize three integers A, B, and C.
3.    For each element x in arr, apply the given equation Axx + B*x + C and store the result in arr.
4.    Sort the array arr using a sorting algorithm.
5.    Print the sorted array arr.

Below is the implementation of the approach:

## C++

 `// C++ code for the approach`   `#include` `using` `namespace` `std;`   `// Function to apply the given equation on each element of the array` `void` `applyEquation(``int` `arr[], ``int` `n, ``int` `a, ``int` `b, ``int` `c) {` `      ``// traversing array and updating each value` `      ``// as per equation` `    ``for``(``int` `i=0; i

## Java

 `import` `java.util.Arrays;`   `public` `class` `ArrayEquation {` `    ``// Function to apply the given equation on each element of the array` `    ``public` `static` `void` `applyEquation(``int``[] arr, ``int` `n, ``int` `a, ``int` `b, ``int` `c) {` `        ``// Traversing the array and updating each value as per the equation` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``arr[i] = a * arr[i] * arr[i] + b * arr[i] + c;` `        ``}` `    ``}`   `    ``// Driver's code` `    ``public` `static` `void` `main(String[] args) {` `        ``// Input array` `        ``int``[] arr = { -``21``, -``15``, ``12``, ``13``, ``14` `};` `        ``int` `n = arr.length;`   `        ``int` `a = -``6``, b = -``7``, c = ``2``;`   `        ``// Function call` `        ``applyEquation(arr, n, a, b, c);`   `        ``// Sorting the modified array` `        ``Arrays.sort(arr);`   `        ``// Printing the sorted array` `        ``System.out.print(``"Array after sorting is: "``);` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``System.out.print(arr[i] + ``" "``);` `        ``}` `    ``}` `}`

## Python3

 `# Function to apply the given equation on each element of the array` `def` `applyEquation(arr, n, a, b, c):` `    ``# Traversing array and updating each value as per equation` `    ``for` `i ``in` `range``(n):` `        ``arr[i] ``=` `a ``*` `arr[i] ``*` `arr[i] ``+` `b ``*` `arr[i] ``+` `c`   `# Driver's code` `if` `__name__ ``=``=` `'__main__'``:` `    ``# Input array` `    ``arr ``=` `[``-``21``, ``-``15``, ``12``, ``13``, ``14``]` `    ``n ``=` `len``(arr)`   `    ``a ``=` `-``6` `    ``b ``=` `-``7` `    ``c ``=` `2`   `    ``# Function call` `    ``applyEquation(arr, n, a, b, c)`   `    ``# Sorting the modified array` `    ``arr.sort()`   `    ``# Printing the sorted array` `    ``print``(``"Array after sorting is:"``, arr)`

## C#

 `using` `System;`   `public` `class` `ArrayEquation` `{` `    ``// Function to apply the given equation on each element of the array` `    ``public` `static` `void` `ApplyEquation(``int``[] arr, ``int` `n, ``int` `a, ``int` `b, ``int` `c)` `    ``{` `        ``// Traversing the array and updating each value as per the equation` `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``arr[i] = a * arr[i] * arr[i] + b * arr[i] + c;` `        ``}` `    ``}`   `    ``// Driver's code` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``// Input array` `        ``int``[] arr = { -21, -15, 12, 13, 14 };` `        ``int` `n = arr.Length;`   `        ``int` `a = -6, b = -7, c = 2;`   `        ``// Function call` `        ``ApplyEquation(arr, n, a, b, c);`   `        ``// Sorting the modified array` `        ``Array.Sort(arr);`   `        ``// Printing the sorted array` `        ``Console.Write(``"Array after sorting is: "``);` `        ``foreach` `(``int` `num ``in` `arr)` `        ``{` `            ``Console.Write(num + ``" "``);` `        ``}` `    ``}` `}`

## Javascript

 `function` `applyEquation(arr, a, b, c) {` `    ``// Traversing the array and updating each value as per the equation` `    ``for` `(let i = 0; i < arr.length; i++) {` `        ``arr[i] = a * arr[i] * arr[i] + b * arr[i] + c;` `    ``}` `}`   `// Driver's code` `function` `main() {` `    ``// Input array` `    ``const arr = [-21, -15, 12, 13, 14];` `    ``const a = -6, b = -7, c = 2;`   `    ``// Function call` `    ``applyEquation(arr, a, b, c);`   `    ``// Sorting the modified array` `    ``arr.sort((x, y) => x - y);`   `    ``// Printing the sorted array` `    ``console.log(``"Array after sorting is: "` `+ arr.join(``" "``));` `}`   `main();`

Output

```Array after sorting is : -2497 -1272 -1243 -1103 -946
```

Time Complexity: O(n * log2n) as sort function has been called. Here, n is the size of the input array.
Auxiliary Space: O(1) as no extra space has been used.

Method 2(Efficient): Parabolic Property:

The equation given is parabolic. So the result of applying it to a sorted array will result in an array that will have a maximum/minimum with the sub-arrays to its left and right sorted.
In the above example, maximum is 0 and the subarray to its left {-4, -1} is sorted in ascending order and the sub-array to its right {-1, -4, -9} is sorted in descending order.
All we need to do is merge these sorted arrays which are linear in time.

So the algorithm is:

1. Apply equation on each element.
2. Find maximum/minimum.
3. Merge sub-arrays.

Note: The below code assumes that the modified array is first increasing then decreasing.

Implementation:

## C++

 `// C program to sort an array after applying equation` `// A*x*x + B*x + C` `#include` `using` `namespace` `std;`   `// Function to sort an array after applying given` `// equation.` `void` `sortArray(``int` `arr[], ``int` `n, ``int` `A, ``int` `B, ``int` `C)` `{` `   ``// Apply equation on all elements` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``arr[i] = A*arr[i]*arr[i] + B*arr[i] + C;`   `    ``// Find maximum element in resultant array` `    ``int` `index, maximum = INT_MIN;` `    ``for` `(``int` `i = 0; i< n; i++)` `    ``{` `        ``if` `(maximum < arr[i])` `        ``{` `            ``index = i;` `            ``maximum = arr[i];` `        ``}` `    ``}`   `    ``// Use maximum element as a break point` `    ``// and merge both subarrays using simple` `    ``// merge function of merge sort` `    ``int` `i = 0, j = n-1;` `    ``int` `new_arr[n], k = 0;` `    ``while` `(i < index && j > index)` `    ``{` `        ``if` `(arr[i] < arr[j])` `            ``new_arr[k++] = arr[i++];` `        ``else` `            ``new_arr[k++] = arr[j--];` `    ``}`   `    ``// Merge remaining elements` `    ``while` `(i < index)` `        ``new_arr[k++] = arr[i++];` `    ``while` `(j > index)` `        ``new_arr[k++] = arr[j--];`   `    ``new_arr[n-1] = maximum;`   `    ``// Modify original array` `    ``for` `(``int` `i = 0; i < n ; i++)` `        ``arr[i] = new_arr[i];` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = {-21 ,-15, 12, 13, 14 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``int` `A = -6, B =-7, C = 2;`   `    ``sortArray(arr, n, A, B, C);`   `    ``cout << ``"Array after sorting is : "``;` `    ``for` `(``int` `i=0; i

## Java

 `// Java program to sort an array after applying equation` `// A*x*x + B*x + C`   `class` `Main` `{` `    ``// Function to sort an array after applying given` `    ``// equation.` `    ``static` `void` `sortArray(``int` `arr[], ``int` `n, ``int` `A, ``int` `B, ``int` `C)` `    ``{` `       ``// Apply equation on all elements` `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``arr[i] = A*arr[i]*arr[i] + B*arr[i] + C;` `     `  `        ``// Find maximum element in resultant array` `        ``int` `index=-``1``;` `        ``int` `maximum = -``999999``;` `        ``for` `(``int` `i = ``0``; i< n; i++)` `        ``{` `            ``if` `(maximum < arr[i])` `            ``{` `                ``index = i;` `                ``maximum = arr[i];` `            ``}` `        ``}` `     `  `        ``// Use maximum element as a break point` `        ``// and merge both subarrays using simple` `        ``// merge function of merge sort` `        ``int` `i = ``0``, j = n-``1``;` `        ``int``[] new_arr = ``new` `int``[n];` `        ``int` `k = ``0``;` `        ``while` `(i < index && j > index)` `        ``{` `            ``if` `(arr[i] < arr[j])` `                ``new_arr[k++] = arr[i++];` `            ``else` `                ``new_arr[k++] = arr[j--];` `        ``}` `     `  `        ``// Merge remaining elements` `        ``while` `(i < index)` `            ``new_arr[k++] = arr[i++];` `        ``while` `(j > index)` `            ``new_arr[k++] = arr[j--];` `     `  `        ``new_arr[n-``1``] = maximum;` `     `  `        ``// Modify original array` `        ``for` `(``int` `p = ``0``; p < n ; p++)` `            ``arr[p] = new_arr[p];` `    ``}` `    `  `    ``// main function` `    ``public` `static` `void` `main (String[] args) ` `    ``{` `        ``int` `arr[] = {-``21` `,-``15``, ``12``, ``13``, ``14` `};` `        ``int` `n = arr.length;` `        ``int` `A = -``6``, B =-``7``, C = ``2``;` `     `  `        ``sortArray(arr, n, A, B, C);` `     `  `        ``System.out.println(``"Array after sorting is : "``);` `        ``for` `(``int` `i=``0``; i

## Python3

 `# Python3 program to sort an ` `# array after applying equation ` `# A*x*x + B*x + C ` `import` `sys`   `# Function to sort an array ` `# after applying given equation. ` `def` `sortArray(arr, n, A, B, C):`   `    ``# Apply equation on all elements ` `    ``for` `i ``in` `range``(n):` `        ``arr[i] ``=` `(A ``*` `arr[i] ``*` `arr[i] ``+` `                  ``B ``*` `arr[i] ``+` `C)` `    ``index ``=` `-``(sys.maxsize ``-` `1``)` `    ``maximum ``=` `-``(sys.maxsize ``-` `1``)` `    `  `    ``# Find maximum element in` `    ``# resultant array` `    ``for` `i ``in` `range``(n):` `        ``if` `maximum < arr[i]:` `            ``index ``=` `i` `            ``maximum ``=` `arr[i]` `    `  `    ``# Use maximum element as a break point ` `    ``# and merge both subarrays using simple ` `    ``# merge function of merge sort ` `    ``i ``=` `0``; j ``=` `n ``-` `1``;` `    ``new_arr ``=` `[``0``] ``*` `n` `    ``k ``=` `0` `    ``while` `i < index ``and` `j > index:` `        ``if` `arr[i] < arr[j]:` `            ``new_arr[k] ``=` `arr[i]` `            ``k ``+``=` `1` `            ``i ``+``=` `1` `        ``else``:` `            ``new_arr[k] ``=` `arr[j]` `            ``k ``+``=` `1` `            ``j ``-``=` `1`   `    ``# Merge remaining elements ` `    ``while` `i < index:` `        ``new_arr[k] ``=` `arr[i]` `        ``k ``+``=` `1` `        ``i ``+``=` `1`   `    ``# Modify original array ` `    ``while` `j > index:` `        ``new_arr[k] ``=` `arr[j]` `        ``k ``+``=` `1` `        ``j ``-``=` `1` `        ``new_arr[n ``-` `1``] ``=` `maximum `   `    ``for` `i ``in` `range``(n):` `        ``arr[i] ``=` `new_arr[i]`   `# Driver code` `arr ``=` `[``-``21``, ``-``15``, ``12``, ``13``, ``14``]` `n ``=` `len``(arr)` `A ``=` `-``6` `B``=` `-``7` `C ``=` `2` `sortArray(arr, n, A, B, C)` `print``(``"Array after sorting is:"``)` `for` `i ``in` `range``(n):` `    ``print``(arr[i], end ``=` `" "``)`   `# This code is contributed ` `# by Shrikant13`

## C#

 `// C# program to sort an array after applying equation ` `// A*x*x + B*x + C ` ` `  `using` `System; ` `class` `MAIN ` `{ ` `    ``// Function to sort an array after applying given ` `    ``// equation. ` `    ``static` `void` `sortArray(``int``[] arr, ``int` `n, ``int` `A, ``int` `B, ``int` `C) ` `    ``{ ` `       ``// Apply equation on all elements ` `        ``for` `(``int` `i = 0; i < n; i++) ` `            ``arr[i] = A*arr[i]*arr[i] + B*arr[i] + C; ` `       `  `        ``// Find maximum element in resultant array ` `        ``int` `index=-1; ` `        ``int` `maximum = -999999; ` `        ``for` `(``int` `i = 0; i< n; i++) ` `        ``{ ` `            ``if` `(maximum < arr[i]) ` `            ``{ ` `                ``index = i; ` `                ``maximum = arr[i]; ` `            ``} ` `        ``} ` `       `  `        ``// Use maximum element as a break point ` `        ``// and merge both subarrays using simple ` `        ``// merge function of merge sort ` `        ``int` `l = 0, j = n-1; ` `        ``int``[] new_arr = ``new` `int``[n]; ` `        ``int` `k = 0; ` `        ``while` `(l < index && j > index) ` `        ``{ ` `            ``if` `(arr[l] < arr[j]) ` `                ``new_arr[k++] = arr[l++]; ` `            ``else` `                ``new_arr[k++] = arr[j--]; ` `        ``} ` `       `  `        ``// Merge remaining elements ` `        ``while` `(l < index) ` `            ``new_arr[k++] = arr[l++]; ` `        ``while` `(j > index) ` `            ``new_arr[k++] = arr[j--]; ` `       `  `        ``new_arr[n-1] = maximum; ` `       `  `        ``// Modify original array ` `        ``for` `(``int` `p = 0; p < n ; p++) ` `            ``arr[p] = new_arr[p]; ` `    ``} ` `      `  `    ``// main function ` `    ``public` `static` `void` `Main ()  ` `    ``{ ` `        ``int``[] arr = {-21 ,-15, 12, 13, 14 }; ` `        ``int` `n = arr.Length; ` `        ``int` `A = -6, B =-7, C = 2; ` `       `  `        ``sortArray(arr, n, A, B, C); ` `       `  `        ``Console.Write(``"Array after sorting is : "``+``"\n"``); ` `        ``for` `(``int` `i=0; i

## Javascript

 ``

## PHP

 ` ``\$index``)` `    ``{` `        ``if` `(``\$arr``[``\$i``] < ``\$arr``[``\$j``])` `            ``array_push``(``\$new_arr``, ``\$arr``[``\$i``++]);` `        ``else` `            ``array_push``(``\$new_arr``, ``\$arr``[``\$j``--]);` `    ``}`   `    ``// Merge remaining elements` `    ``while` `(``\$i` `< ``\$index``)` `        ``array_push``(``\$new_arr``, ``\$arr``[``\$i``++]);` `    ``while` `(``\$j` `> ``\$index``)` `        ``array_push``(``\$new_arr``, ``\$arr``[``\$j``--]);`   `    ``array_push``(``\$new_arr``, ``\$maximum``);`   `    ``// Modify original array` `    ``for` `(``\$i` `= 0; ``\$i` `< ``count``(``\$new_arr``) ; ``\$i``++)` `        ``\$arr``[``\$i``] = ``\$new_arr``[``\$i``];` `}`   `// Driver code` `\$arr` `= ``array``(-21 ,-15, 12, 13, 14 );` `\$n` `= ``count``(``\$arr``);` `\$A` `= -6;` `\$B` `= -7;` `\$C` `= 2;`   `sortArray(``\$arr``, ``\$n``, ``\$A``, ``\$B``, ``\$C``);`   `echo` `"Array after sorting is : \n"``;` `for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++)` `    ``echo` `\$arr``[``\$i``] . ``" "``;`   `// This code is contributed by mits` `?>`

Output

```Array after sorting is : n-2497 -1272 -1243 -1103 -946
```

Time Complexity: O(n)
Auxiliary Space: O(n)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next