Monday, 18 September 2017

Finding the next greater number using same set of digits


Next Greater Number Using Same Set of Digits :

Implement the next permutation, which rearranges numbers into the numerically next greater permutation of numbers.
If such arrangement is not possible, it must be rearranged as the lowest possible order ie, sorted in an ascending order.

For example:
                      1,2,3 → 1,3,2
                      3,2,1 → 1,2,3

Algorithm :
Let the input be { 2, 1, 8, 7, 6, 5 } 

Step 1: Iterate from n-2 th index to 0th index . If for any 'i' , arr[i]<arr[i+1] , stop the iteration.
                            { 2, 1, 8, 7, 6, 5 }

Step 2: Find out the number which is greater than ith element and lesser than i+1 th element. Let this index be j.
                            { 2, 1, 8, 7, 6, 5 }

Step 3: Swap the elements at index i and j.
                          { 2, 5, 8, 7, 6, 1 }

Step 4: Sort the elements after ith index.
                            { 2, 5, 1, 6, 7, 8 }

Program :

#include <stdio.h>
#include <stdlib.h>

//Swapping function
void swap(int *a,int *b)
{
       int t=*a;
       *a=*b;
       *b=t;
}



/* Comparison function. Receives two generic (void) pointers to the items under comparison. */
int compare(const void *a,const void *b)
{
       return *(int*)a-*(int*)b;
}
int findceil(int a[],int k,int l,int h)
{
      int index=l,i;
      for(i=l+1;i<h;i++)
      {
            if(a[i]>k && a[i]<a[index])
                  index=i;
      }
    return index;
}

void find(int a[],int n)
{
    int i;
    for(i=n-2;i>=0;i--)
         if(a[i]<a[i+1])break;
                 if(i==-1)
                 {
                   qsort(a,n,sizeof(a[0]),compare);
                   return;
                  }
         int ceilindex=findceil(a,a[i],i+1,n);
         swap(&a[i],&a[ceilindex]);
         qsort(a+i+1,n-i-1,sizeof(a[0]),compare);
        //Syntax of qsort
}

int main() 
{
        int n;

               scanf("%d",&n);
        int a[n],i;
        for(i=0;i<n;i++)scanf("%d",&a[i]);
               find(a,n);
        for(i=0;i<n;i++)printf("%d ",a[i]);
               printf("\n");
    return 0;
}

No comments:

Post a Comment