Friday, January 29, 2016

Sort 3 numbers array

Sort 3 numbers array


Sort an array which has values 1, 2 and 3 with n comparisons only.
input : {1,2,3,2,3,1,2,3,3,2,2,2,3,1,2,1,1,3,3,2,2,1,2,2,3,2,2,2,1,3,1}
output: 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3
Sol:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Sort an array which has numbers 1, 2 and 3
int[] Sort(int[] a)
{
    int i,j;
    for(i=0,j=a.length-1; i<j;)
    {
        if(a[i]==1)
        {
            i++;
        }
        else if(a[j]==3)
        {
            j--;
        }
        else if(a[i]>a[j] && a[i]==3)
        {               
            Swap(a,i,j);
        }
        else if(a[i]>a[j] && a[j]==1)
        {
            Swap(a,i,j);
        }
        else
        {
         // both values are 2
            int k=i+1;
            while(a[k]==a[j] && k<j)
            {
                k++;
            }
            if(j==k)
                break;
            else if(a[k]<a[i] && a[k]==1)
            {
                Swap(a,k,i);
                i++;
            }
            else if(a[k]>a[j]&&a[k]==3)
            {
                Swap(a,k,j);
                j--;
            }              
        }          
    }
    return a;
}
 
void Swap(int[] a, int i, int j)
{
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}

No comments:

Post a Comment