w3resource

C++ Exercises: Sort a given array of 0s, 1s and 2s

C++ Array: Exercise-16 with Solution

Write a C++ program to sort a given array of 0s, 1s and 2s. In the final array put all 0s first, then all 1s and all 2s in last.

Pictorial Presentation:

C++ Exercises: Sort a given  array of  0s, 1s and 2s

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

void swap(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

void sort_012_num(int nums[], int n)
{
    int i = 0;
    int j = n - 1;
    int mid_num = 0;
 
    while (mid_num <= j)
    {
        switch (nums[mid_num])
        {
        case 0:
            swap(&nums[i++], &nums[mid_num++]);
            break;
        case 1:
            mid_num++;
            break;
        case 2:
            swap(&nums[mid_num], &nums[j--]);
            break;
        }
    }
}
 
 
int main()
{
    int nums[] = {0, 1, 2, 2, 1, 1, 0, 0, 1}; 
    int n = sizeof(nums)/sizeof(nums[0]);
   	cout << "Original array: ";
    for (int i=0; i < n; i++) 
    cout << nums[i] <<" ";
    sort_012_num(nums, n);
 
    printf("\nArray elements after rearranging: ");
      for (int i=0; i < n; i++) 
      cout << nums[i] <<" ";
        return 0;
      }

Sample Output:

Original array: 0 1 2 2 1 1 0 0 1 
Array elements after rearranging: 0 0 0 1 1 1 1 2 2    

Flowchart:

Flowchart: Sort a given  array of  0s, 1s and 2s

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to rearrange a given sorted array of positive integers.
Next: Write a C++ program to sort (in descending order) an array in of distinct elements according to absolute difference of array elements and with a given value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1

Ref: https://bit.ly/3PWhs5N