132k views
4 votes
Create a sort_bigger_half() function with a vector of integers passed as an argument. Function should divide the vector into two parts and sort the part in which sum of elements is bigger. Function should return altered vector.

1 Answer

1 vote

Final answer:

To create the sort_bigger_half() function, you can follow these steps: Calculate the sum of all the elements in the vector. Divide the vector into two equal parts. Compare the sums of the two parts. Sort the part with the larger sum using a sorting algorithm. Finally, return the altered vector.

Step-by-step explanation:

To create the sort_bigger_half() function, you can follow these steps:

  1. Calculate the sum of all the elements in the vector.
  2. Divide the vector into two equal parts.
  3. Compare the sums of the two parts.
  4. Sort the part with the larger sum using a sorting algorithm.
  5. Finally, return the altered vector.

Here's an example implementation:

vector sort_bigger_half(vector& nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
int halfSum = sum / 2;

sort(nums.begin(), nums.end());
int currSum = 0;
vector result;

for (int i = nums.size() - 1; i >= 0; i--) {
currSum += nums[i];
result.push_back(nums[i]);
if (currSum >= halfSum) {
break;
}
}

sort(result.begin(), result.end());
return result;
}

User Willeman
by
8.2k points