Find a partition point in array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to find the partition point in an array where all the elements left to the partition point are small and all the elements right to the partition point are large.

Let's see the steps to solve the problem.

  • Initialize the array.

  • Iterate over the array.

    • Iterate from 0 to I and check each value whether it is smaller than the current value or not.

    • Iterate from I to n and check each value whether it is larger than the current value or not.

    • If the bot the conditions satisfied, then return the value.

  • Print the partition point.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findPartitionElement(int arr[], int n) {
   for (int i = 0; i < n; i++) {
      int is_found = true;
      for (int j = 0; j < i; j++) {
         if (arr[j] >= arr[i]) {
            is_found = false;
            break;
         }
      }
      for (int j = i + 1; j < n; j++) {
         if (arr[j] <= arr[i]) {
            is_found = false;
            break;
         }
      }
      if (is_found) {
         return arr[i];
      }
   }
   return -1;
}
int main() {
   int arr[] = { 4, 3, 5, 6, 7 };
   cout << findPartitionElement(arr, 5) << endl;
   return 0;
}

Output

If you execute the above code, then you will get the following result.

5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Feb-2021 11:56:41
Advertisements