Programs


Title : Program to sort an array of 0s, 1s and 2s.

#include <stdio.h>

void changePlace(int arr1[], int i, int j)

{

   int tmp = arr1[i];

   arr1[i] = arr1[j];

   arr1[j] = tmp;

}

int sortElements(int arr1[], int end)

{

   int start = 0, mid = 0;

   int pivot = 1;

   while (mid <= end)

   {

       if (arr1[mid] < pivot)

       {

           changePlace(arr1, start, mid);

           ++start, ++mid;

       }

       else if (arr1[mid] > pivot)

       {

           changePlace(arr1, mid, end);

           --end;

       }

       else

       {

           ++mid;

       }

   }

}

int main()

{

   int arr1[] = {0, 2, 1, 1, 2, 2, 0, 0, 0, 2, 1, 1};

   int n = sizeof(arr1) / sizeof(arr1[0]);

   int i;

     printf("The given array is :  ");

   for (i = 0; i < n; i++)

   {

       printf("%d  ", arr1[i]);

   }

   printf("\n");

   printf("After sortig the elements in the array are: \n");

   sortElements(arr1, n - 1);

   for (int i = 0; i < n; i++)

   {

       printf("%d ", arr1[i]);

   }

   return 0;

}

OUTPUT:

The given array is :  0  2  1  1  2  2  0  0  0  2  1  1 

After sortig the elements in the array are:

0 0 0 0 1 1 1 1 2 2 2 2

Related Topics

  • Integer x appears more than n by 2 times in sorted array

      Jan 15, 2022

  • Program to find majority element of an array

      Jan 03, 2022

  • Program to print a matrix in spiral form

      Jan 03, 2022

  • WAP to find the maximum circular sub array sum of given array

      Jan 03, 2022

  • Program to count the number of triangles from a given array

      Jan 03, 2022

  • WAP to find the number of times occurs a given number in an array

      Jan 03, 2022

  • Subscribe Now