```
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(),nums.end());
/* Sort the vector to find the median. Note that though this takes O(nlogn) time, it can be done in O(n) using Quick Select Algorithm.*/
int median = nums[nums.size()/2]; // Works for both odd and even number of elements
int res = 0;
for(int i=0;i<nums.size();i++)
{
res += abs(nums[i]-median); // How far is each element from median
}
return res;
}};
```