Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Print array of strings in sorted order without copying one string into another
Next article icon

Sort an array after applying the given equation

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an integer array arr[] sorted in ascending order, along with three integers: A, B, and C. The task is to transform each element x in the array using the quadratic function A*(x^2) + B*x + C. After applying this transformation to every element, return the modified array in sorted order.

Examples:

Input: arr[] = [-4, -2, 0, 2, 4], A = 1, B = 3, C = 5
Output: [3, 5, 9, 15, 33]
Explanation: After applying f(x) = 1*x2+ 3*x + 5 to each x, we get [9, 3, 5, 15, 33]. After sorting this array, the array becomes [3, 5, 9, 15, 33].

Input: arr[] = [-3, -1, 2, 4], A = -1, B = 0, C = 0
Output: [-16, -9, -4, -1]
Explanation: After applying f(x) = -1*x2 to each x, we get [-9, -1, -4, -16 ]. After sorting this array, the array becomes [-16, -9, -4, -1].

Input: arr[] = [-1, 0, 1, 2, 3, 4], A = -1, B = 2, C = -1
Output: [-9, -4, -4, -1, -1, 0]

Table of Content

  • [Brute Force Approach] Apply the Equation and Sort - O(n*log(n)) Time and O(1) Space
  • [Expected Approach] Using Two Pointers - O(n) Time and O(n) Space

[Brute Force Approach] Apply the Equation and Sort - O(n*log(n)) Time and O(1) Space

The idea is to directly transform each element in the array, i.e. for each element x in arr[], apply the given equation A*x2 + B*x + C in-place and then simply sort the array in ascending order.

C++
#include <bits/stdc++.h> using namespace std;  // Function to apply quadratic transformation int evaluate(int x, int A, int B, int C) {     return A * x * x + B * x + C; }  // Function to transform and sort the array in-place vector<int> sortArray(vector<int> &arr, int A, int B, int C) {     int n = arr.size();          vector<int> transformed;     // Apply the transformation     for (int i = 0; i < n; i++) {         transformed.push_back(evaluate(arr[i], A, B, C));     }      // Sort the transformed array     sort(transformed.begin(), transformed.end());      return transformed; }  int main() {     vector<int> arr = {-4, -2, 0, 2, 4};     int A = 1, B = 3, C = 5;      vector<int> res = sortArray(arr, A, B, C);      for (int val : res) {         cout << val << " ";     }      return 0; } 
Java
import java.util.*;  class GfG {      // Function to apply quadratic transformation     static int evaluate(int x, int A, int B, int C) {         return A * x * x + B * x + C;     }      // Function to transform and sort the array (returns ArrayList<Integer>)     static ArrayList<Integer> sortArray(int[] arr, int A, int B, int C) {         int n = arr.length;         Integer[] transformed = new Integer[n];          // Apply the transformation and store in array         for (int i = 0; i < n; i++) {             transformed[i] = evaluate(arr[i], A, B, C);         }          // Sort the array         Arrays.sort(transformed);          // Convert to ArrayList and return         return new ArrayList<>(Arrays.asList(transformed));     }      public static void main(String[] args) {         int[] arr = {-4, -2, 0, 2, 4};         int A = 1, B = 3, C = 5;          ArrayList<Integer> res = sortArray(arr, A, B, C);          for (int val : res) {             System.out.print(val + " ");         }     } } 
Python
# Python Code to Sort array after applying # equation using Brute Force Approach  # Function to apply quadratic transformation def evaluate(x, A, B, C):     return A * x * x + B * x + C  # Function to transform and sort the array, returning a new list def sortArray(arr, A, B, C):     # Create a new array with the transformed values     transformed = [evaluate(x, A, B, C) for x in arr]          # Sort the transformed array     transformed.sort()          return transformed  if __name__ == "__main__":     arr = [-4, -2, 0, 2, 4]     A, B, C = 1, 3, 5      res = sortArray(arr, A, B, C)      for val in res:         print(val, end=" ") 
C#
using System; using System.Collections.Generic;  class GfG{     // Function to apply quadratic transformation     static int evaluate(int x, int A, int B, int C){                  return A * x * x + B * x + C;     }      // Function to transform and sort the array (returns List<int>)     static List<int> sortArray(int[] arr, int A, int B, int C){                  int n = arr.Length;         int[] transformed = new int[n];          // Apply transformation         for (int i = 0; i < n; i++){                          transformed[i] = evaluate(arr[i], A, B, C);         }          // Sort the transformed array         Array.Sort(transformed);          // Convert to List<int> and return         return new List<int>(transformed);     }      static void Main(){                  int[] arr = { -4, -2, 0, 2, 4 };         int A = 1, B = 3, C = 5;          List<int> res = sortArray(arr, A, B, C);          foreach (int val in res){                          Console.Write(val + " ");         }     } } 
JavaScript
// JavaScript Code to Sort array after applying // equation using Brute Force Approach  // Function to apply quadratic transformation function evaluate(x, A, B, C) {     return A * x * x + B * x + C; }  // Function to transform and sort the array in-place function sortArray(arr, A, B, C) {     let n = arr.length;          let transformed = [];     // Apply the transformation in-place     for (let i = 0; i < n; i++) {         transformed.push(evaluate(arr[i], A, B, C));     }      // Sort the transformed array     transformed.sort((a, b) => a - b);      return transformed; }  // Driver Code let arr = [-4, -2, 0, 2, 4]; let A = 1, B = 3, C = 5;  let res = sortArray(arr, A, B, C);  for (let val of res) {     process.stdout.write(val + " "); } 

Output
3 5 9 15 33  

[Expected Approach] Using Two Pointers - O(n) Time and O(n) Space

The idea is to use the fact that input array is sorted and apply a Two-Pointer approach. After applying the quadratic transformation to each element, the smallest and largest values will always be at the ends of the array (Why? 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)

We process from both ends using two pointers (left and right) moving towards each other. By comparing the transformed values of arr[left] and arr[right], we can fill a new array (newArr) starting either from the front or the back depending on whether the coefficient A is positive or negative. The observation here is:

  • if A >= 0, the largest values will be at the end
  • while if A < 0, the largest values will be at the beginning.

Step-by-Step Implementation:

  • Start by initializing two pointers: left at the beginning and right at the end of the array.
  • Create a new array newArr of the same size to store the transformed and sorted values.
  • Determine the index where you will start filling newArr based on whether A is positive or negative.
  • Loop through the array using the left and right pointers, comparing the transformed values of arr[left] and arr[right].
  • Depending on the sign of A, place the larger of the two values at the appropriate position in newArr.
  • After processing all elements, copy the sorted values from newArr back to the original arr.
  • Finally, return the modified arr containing the transformed and sorted values.
C++
#include <bits/stdc++.h> using namespace std;  // Function to apply quadratic transformation int evaluate(int x, int A, int B, int C) {     return A * x * x + B * x + C; }  // Function to transform and sort the array  vector<int> sortArray(vector<int> &arr, int A, int B, int C) {     int n = arr.size();     vector<int> newArr(n);      int left = 0, right = n - 1;     int index = (A >= 0) ? n - 1 : 0;      // Two-pointer approach to fill newArr      while (left <= right) {         int leftVal = evaluate(arr[left], A, B, C);         int rightVal = evaluate(arr[right], A, B, C);          if (A >= 0) {             if (leftVal > rightVal) {                 newArr[index--] = leftVal;                 left++;             } else {                 newArr[index--] = rightVal;                 right--;             }         } else {             if (leftVal < rightVal) {                 newArr[index++] = leftVal;                 left++;             } else {                 newArr[index++] = rightVal;                 right--;             }         }     }      return newArr; }  int main() {     vector<int> arr = {-4, -2, 0, 2, 4};     int A = 1, B = 3, C = 5;      vector<int> res = sortArray(arr, A, B, C);      for (int val : res) {         cout << val << " ";     }      return 0; } 
Java
import java.util.*;  class GfG {      // Function to apply quadratic transformation     public static int evaluate(int x, int A, int B, int C) {         return A * x * x + B * x + C;     }      // Function to transform and sort the array     public static ArrayList<Integer> sortArray(int[] arr, int A, int B, int C) {         int n = arr.length;         int[] newArr = new int[n];          int left = 0, right = n - 1;         int index = (A >= 0) ? n - 1 : 0;          // Two-pointer approach to fill newArr from end or start         while (left <= right) {             int leftVal = evaluate(arr[left], A, B, C);             int rightVal = evaluate(arr[right], A, B, C);              if (A >= 0) {                 if (leftVal > rightVal) {                     newArr[index--] = leftVal;                     left++;                 } else {                     newArr[index--] = rightVal;                     right--;                 }             } else {                 if (leftVal < rightVal) {                     newArr[index++] = leftVal;                     left++;                 } else {                     newArr[index++] = rightVal;                     right--;                 }             }         }          // Convert array to ArrayList and return         ArrayList<Integer> result = new ArrayList<>();         for (int val : newArr) {             result.add(val);         }          return result;     }      public static void main(String[] args) {         int[] arr = {-4, -2, 0, 2, 4};         int A = 1, B = 3, C = 5;          ArrayList<Integer> res = sortArray(arr, A, B, C);          for (int val : res) {             System.out.print(val + " ");         }     } } 
Python
# Python Code to Sort array after applying # equation using Two Pointer Approach  # Function to apply quadratic transformation def evaluate(x, A, B, C):     return A * x * x + B * x + C  # Function to transform and sort the array def sortArray(arr, A, B, C):     n = len(arr)     newArr = [0] * n      left, right = 0, n - 1     index = n - 1 if A >= 0 else 0      # Two-pointer approach to fill newArr     # from end or start     while left <= right:         leftVal = evaluate(arr[left], A, B, C)         rightVal = evaluate(arr[right], A, B, C)          if A >= 0:             # Fill from end             if leftVal > rightVal:                 newArr[index] = leftVal                 left += 1                 index -= 1             else:                 newArr[index] = rightVal                 right -= 1                 index -= 1         else:             # Fill from start             if leftVal < rightVal:                 newArr[index] = leftVal                 left += 1                 index += 1             else:                 newArr[index] = rightVal                 right -= 1                 index += 1      return newArr   if __name__ == "__main__":     arr = [-4, -2, 0, 2, 4]     A = 1     B = 3     C = 5      res = sortArray(arr, A, B, C)     print(*res) 
C#
using System; using System.Collections.Generic;  class GfG {      // Function to apply quadratic transformation     public static int evaluate(int x, int A, int B, int C) {         return A * x * x + B * x + C;     }      // Function to transform and sort the array     public static List<int> sortArray(int[] arr, int A, int B, int C) {         int n = arr.Length;         int[] newArr = new int[n];          int left = 0, right = n - 1;         int index = (A >= 0) ? n - 1 : 0;          // Two-pointer approach to fill newArr         while (left <= right) {             int leftVal = evaluate(arr[left], A, B, C);             int rightVal = evaluate(arr[right], A, B, C);              if (A >= 0) {                 if (leftVal > rightVal) {                     newArr[index--] = leftVal;                     left++;                 } else {                     newArr[index--] = rightVal;                     right--;                 }             } else {                 if (leftVal < rightVal) {                     newArr[index++] = leftVal;                     left++;                 } else {                     newArr[index++] = rightVal;                     right--;                 }             }         }          return new List<int>(newArr);     }      public static void Main(string[] args) {         int[] arr = {-4, -2, 0, 2, 4};         int A = 1, B = 3, C = 5;          List<int> res = sortArray(arr, A, B, C);          foreach (int val in res) {             Console.Write(val + " ");         }     } } 
JavaScript
// JavaScript Code to Sort array after applying // equation using Two Pointer Approach  // Function to apply quadratic transformation function evaluate(x, A, B, C) {     return A * x * x + B * x + C; }  // Function to transform and sort the array function sortArray(arr, A, B, C) {     let n = arr.length;     let newArr = new Array(n);      let left = 0, right = n - 1;     let index = (A >= 0) ? n - 1 : 0;      // Two-pointer approach to fill newArr     // from end or start     while (left <= right) {         let leftVal = evaluate(arr[left], A, B, C);         let rightVal = evaluate(arr[right], A, B, C);          if (A >= 0) {             // Fill from end             if (leftVal > rightVal) {                 newArr[index] = leftVal;                 left++;                 index--;             } else {                 newArr[index] = rightVal;                 right--;                 index--;             }         } else {             // Fill from start             if (leftVal < rightVal) {                 newArr[index] = leftVal;                 left++;                 index++;             } else {                 newArr[index] = rightVal;                 right--;                 index++;             }         }     }      // Assign values back to arr     for (let i = 0; i < n; i++) {         arr[i] = newArr[i];     }      return arr; }  // Driver Code let arr = [-4, -2, 0, 2, 4]; let A = 1, B = 3, C = 5;  let res = sortArray(arr, A, B, C);  console.log(res.join(' ')); 

Output
3 5 9 15 33 

Next Article
Print array of strings in sorted order without copying one string into another
author
kartik
Improve
Article Tags :
  • Sorting
  • Mathematical
  • DSA
  • Arrays
  • Adobe
  • two-pointer-algorithm
Practice Tags :
  • Adobe
  • Arrays
  • Mathematical
  • Sorting
  • two-pointer-algorithm

Similar Reads

  • Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
  • Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read
  • Most Common Sorting Algorithms

    • Selection Sort
      Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
      8 min read
    • Bubble Sort Algorithm
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
      8 min read
    • Insertion Sort Algorithm
      Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
      9 min read
    • Merge Sort - Data Structure and Algorithms Tutorials
      Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
      14 min read
    • Quick Sort
      QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
      13 min read
    • Heap Sort - Data Structures and Algorithms Tutorials
      Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
      14 min read
    • Counting Sort - Data Structures and Algorithms Tutorials
      Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
      9 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences