C++ code to count operations to make array sorted

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements (n is odd). A contains a permutation of first n natural numbers. Let there is a function f(i) this takes single argument i in range 0 to n-2, and does the operation: if A[i] > A[i+1], swap the values of A[i] and A[i+1]. We have to count number of iterations to make array A sorted, for the first time.

So, if the input is like A = [4, 5, 7, 1, 3, 2, 6], then the output will be 5, because the array states after each iteration is like: [4, 5, 1, 7, 2, 3, 6], [4, 1, 5, 2, 7, 3, 6], [1, 4, 2, 5, 3, 7, 6], [1, 2, 4, 3, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7].

Steps

To solve this, we will follow these steps −

n := size of A
f := 0
Ans := 0
for initialize Ans := 0, do:
   f := 0
   for initialize j := 0, when j < n - 1, update (increase j by 1), do:
      if A[j] > A[j + 1], then:
         f := 1
      if not f is non-zero, then:
         Come out from the loop
      for initialize j := (Ans AND 1), when j < n - 1, update j := j + 2, do:
         if A[j] > A[j + 1], then:
            swap A[j] and A[j + 1]
         (increase Ans by 1)
return Ans

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
   int n = A.size();
   bool f = 0;
   int Ans = 0;
   for (Ans = 0;;){
      f = 0;
      for (int j = 0; j < n - 1; j++)
         if (A[j] > A[j + 1])
            f = 1;
      if (!f)
         break;
      for (int j = (Ans & 1); j < n - 1; j += 2)
         if (A[j] > A[j + 1])
            swap(A[j], A[j + 1]);
      Ans++;
   }
   return Ans;
}
int main(){
   vector<int> A = { 4, 5, 7, 1, 3, 2, 6 };
   cout << solve(A) << endl;
}

Input

{ 4, 5, 7, 1, 3, 2, 6 }

Output

5
raja
Updated on 15-Mar-2022 05:59:01

Advertisements