4.Sort an array of 0's, 1's & 2's.

4.Sort an array of 0's, 1's & 2's.


Problem link :- click here


C code

#include<stdio.h>

void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void sort_012(int A[], int n)
{
    int i, j, m;
    i = 0;
    j = n-1;
    m = 0;

    while(m<=j)
    {
        if(A[m] == 0)
        {
            swap(&A[i], &A[m]);
            i++;
            m++;
        }
        else if(A[m] == 1)
        {
            m++;
        }
        else
        {
            swap(&A[j], &A[m]);
            j--;
        }
    }
}

void main()
{
    int arr[30];
    int n, i;

    printf("Enter the size of the array\n");
    scanf("%d",&n);
    printf("Enter the elements of the array(only 0, 1, or 2)\n");
    for(i=0; i<n; i++)
        scanf("%d",&arr[i]);

    printf("Given Array\n");
    for(i=0; i<n; i++)
        printf("\t%d",arr[i]);
    printf("\n");

    sort_012(arr, n);

    printf("\n\nGiven Array after sorting\n");
    for(i=0; i<n; i++)
        printf("\t%d",arr[i]);
    printf("\n");
}

Java code

//Sort array(0,1,2)
package programs;

import java.util.*;

public class Array__4
{

	static void sort012(int arr[], int n)
	{
		int i, j, m, temp;
		i = 0;
		j = n-1;
		m=0;
		
		while(m<=j)
		{
			if(arr[m] == 0)
			{
				temp = arr[i];
				arr[i] = arr[m];
				arr[m] = temp;
				i++;
				m++;
			}
			else if(arr[m] == 1)
				m++;
			else
			{
				temp = arr[j];
				arr[j] = arr[m];
				arr[m] = temp;
				j--;
			}
		}
	}
	
	public static void main(String[] args)
	{
		int array[] = new int[20];
		int n, i;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the size of the array :");
		n = s.nextInt();
		System.out.println("Enter the elements of the array :");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		System.out.println("Given Array :");
		print_array(array, n);
		System.out.println("\n\n");
		
		sort012(array, n);
		System.out.println("Array after sorting");
		print_array(array, n);

	}

	static void print_array(int arr[], int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)



Comments

Popular posts from this blog

1. Reverse

3. Height of Binary tree