[C++] | EASY SORTING WITH CUSTOM COMPARATOR | WELL COMMENTED | O(1) AUXILIARY SPACE |
\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n\t    //we sort the given vector using custom comparator (la
```\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n\t    //we sort the given vector using custom comparator (lambda function)\n        sort(arr.begin(),arr.end(),[&](int &a,int &b){\n            if(abs(x-a)<abs(x-b))return true;          // it should be sorted according to lower absolute difference\n            else if(abs(x-a) == abs(x-b))return a<b;   // if the absolute difference is same we sort it according to the smaller element\n            return false;                              // otherwise we return false\n        });\n        vector<int> ans;\n        for(int i = 0;i<arr.size() && k--;i++){        // we consider the first k elements after sorting\n            ans.push_back(arr[i]);\n        }\n        sort(ans.begin(),ans.end());                  // as we have to return the answer in sorted order, we sort it at the end.\n        return ans;\n    }\n};\n```
['C', 'Sorting', 'C++']