Smallest number possible by swapping adjacent even odd pairs


"Even-odd pairs" means to pairings of two consecutive integers, one is even and the other odd. For example, even-odd pairs include (2,3), (4,5), (6,7), etc.

These pairings are commonly employed in number changing-based algorithms and programming exercises. When repeating over a set of numbers, like, one could only want to carry out operation on even or odd numbers. When this occurs, employing even-odd pairs can aid in code simplification by lowering the number of conditional statements required.

Method

By swapping nearby even-odd pairings, you can apply the following strategies to determine the least number possible −

  • Bubble Sort Method

  • Greedy Approach

Method 1: Bubble Sort Method

Commencing with the number, we must use a bubble sort-sequel algorithm to address the problem at hand. From the start, we must closely examine each pair of adjacent digits. Should the left member of the pair be an odd digit and the right, even, we switch their positions. The process then continues with the subsequent digits after the last two have been addressed. If any changes during a full pass-through occur, we must restart the entire process anew.

Syntax

To get the least number by swapping nearby even-odd pairs, follow this step-by-step tutorial on how to construct the Bubble Sort algorithm in C++ −

  • Create integer array and fill in the numbers to be sorted.

int q[] = {6, 4, 2, 5, 7, 1};
  • Calculate the size or length of the array.

int p = sizeof(q) / sizeof(q[0]);
  • Apply Bubble Sort algorithm.

for (int r = 0; r < p - 1; r++) {
   for (int j = 0; j < p - r - 1; j++) {
      if (q[j] % 2 == 0 && q [j + 1] % 2 != 0) {
          swap(q[j], q [j + 1]);
      }
   }
}
  • Output sorted array.

for (int r = 0; r < p; r++) {
   cout << q[r] << " ";
}

Algorithm

Step-by-step algorithm of bubble sort method to find the smallest number possible by swapping adjacent even-odd pairs −

Step 1 − Start taking a set of numbers that need to be sorted as input.

Step 2 − Create a loop that repeats across array until all the elements are sorted.

Step 3 − Then comes a second loop inside the first one that iterates through every pair of adjacent elements in the array.

Step 4 − Find if the first element is odd and second element is even for each pair of adjacent elements. If so, switch the elements.

Step 5 − If there was a preceding element in the array, compare the newly swapped member with it. Replace the previously swapped element with the one that was smaller if necessary.

Step 6 − Keep going through the array iteratively until every pair has been validated and sorted.

Step 7 − If no swaps were performed during any iteration, the array is regarded as sorted, and the outer loop may be ended.

Step 8 − After sorting is finished, print the array that has been sorted.

Example 1

To get the smallest number by exchanging neighboring even-odd pairings, here is an example implementation of the bubble sort method in C++ −

Using a vector, input numbers undergo sorting in this implementation through the application of the bubble sort algorithm via the bubble Sort function. The swapped variable keeps track of the swaps within the inner loop. Should a pass be completed with no swaps taking place, the algorithm ceases operation, taking advantage of the fact that the list is already sorted.

In the inner loop, we compare each pair of neighboring numbers. Only when the first digit is an odd and the second is an even, or when the parities match and the first number is greater, do we modify the digits. The order of even numbers preceding odd numbers creates a rising order for even-odd pairs.

Using a for loop, the printed output consists of the sorted numbers. If alterations to the even-odd pairings are made between neighboring digits, the result will be producing the smallest possible sequence of 2 7 5 8 9 10 1 12.

#include <iostream>
#include <vector>
using namespace std;

void bubbleSort(vector<int>& nums) {
   int n = nums.size();
   bool swapped;
   for (int i = 0; i < n-1; i++) {
      swapped = false;
      for (int j = 0; j < n-i-1; j++) {
         if ((nums[j] % 2 == 0 && nums[j+1] % 2 != 0) || (nums[j] % 2 == nums[j+1] % 2 && nums[j] > nums[j+1])) {
            swap(nums[j], nums[j+1]);
            swapped = true;
         }
      }
   if (!swapped) break;
   }
}

int main() {
   vector<int> nums = {7, 2, 5, 9, 12, 10, 8, 1};
   bubbleSort(nums);
   for (int num : nums) {
      cout << num << " ";
   }
   cout << endl;  // Output: 2 7 5 8 9 10 1 12
   return 0;
}

Output

1 5 7 9 2 8 10 12

Method 2: Greedy Approach

One more strategy is to always replace the smallest even digit with the largest, odd digit that follows it. This is known as the greedy approach. Locate the largest, odd digit to the right of the leftmost even digit. In this case, switch the two digits and move on to the next step starting with the swapped even digit. The next even digit should be used if there isn't a larger odd digit to the right of the present even digit.

Syntax

Here is a step-by-step C++ code to implement the greedy method to find the smallest number possible by swapping adjacent even-odd pairs −

  • Define a function to swap two adjacent characters in a string −

void swapAdjacentChars(string& s, int i) {
   char temp = s[i];
   s[i] = s[i+1];
   s[i+1] = temp;
}
  • Initialize the string

string s = "98167375";
  • Loop through the string, swapping adjacent even-odd pairs

for (int o = 0; o < s.l () - 1; o++) {
   if ((s[o] - '0') % 2 == 0 && (s[o+1] - '0') % 2! = 0) {
      swap Adjacentn Chars (s, o);
   break;
   }
}
  • Print the result

   cout << s << endl;
}

Algorithm

The greedy algorithm to find the smallest number possible by swapping adjacent even-odd pairs can be implemented using the following steps −

Step 1 − Convert the given number into an array of digits.

Step 2 − Traverse the array from left to right and for each even digit, search for the smallest, odd digit to its right.

Step 3 − If a smaller odd digit is found, swap the even and odd digits, and break the loop.

Step 4 − If no smaller odd digit is found, continue to the next even digit.

Step 5 − Transforming a digit array into a single number presents a seemingly challenging task. Applying a swapping algorithm to the problem, however, can offer a time complexity of O(n^2), with n representing the number of digits in the initial number. Fortunately, the number of swaps required is usually minimal; hence, the solution is both efficient and quick.

Example 2

Here is a C++ example of greedy method, in which we swap neighbouring even-odd pairings to get the least integer conceivable −

In this example, we make a function called smallest number that takes a string num as input and returns the lowest number that can be created by switching neighbouring even-odd pairings. The first time the method iterates through the string, it determines whether the current index is even and the digit at that point is odd. In that situation, it looks for the following even digit in the string and swaps it with the odd digit. The altered string is given back as a conclusion by the function.

#include <iostream>
#include <string>
using namespace std;

string smallestNumber(string num) {
   int n = num.length();

   // Iterate over the string and swap adjacent even-odd pairs
   for (int i = 0; i < n - 1; i++) {
      if (i % 2 == 0 && num[i] % 2 != 0) {
         // Swap the current odd digit with the next even digit
         for (int j = i + 1; j < n; j++) {
            if (j % 2 != 0 && num[j] % 2 == 0) {
               swap(num[i], num[j]);
               break;
            }
         }
      }
   }
   return num;
}

int main() {
   string num = "2145367";
   cout << "Original number: " << num << endl;
   cout << "Smallest number possible: " << smallestNumber(num) << endl;

   return 0;
}

Output

Original number: 2145367
Smallest number possible: 2145637

Conclusion

Starting from the leftmost digit, we can compare it to the adjacent numbers to find the minimal value attainable through an alteration of neighboring even-odd pairings. To create this minimum number, we switch to the two digits if the left one is even and the right one is odd. This procedure continues until the rightmost digit. With this method, we can ensure that the smaller digits occur first in the number, making it the smallest number achievable. In the event of several even-odd pairs of the same value, we initially must contemplate the pair closest to the leftmost digit.

Updated on: 31-Jul-2023

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements