Home > Programming > A simple program to permutate the array elements

A simple program to permutate the array elements


Here is a very simple way to permute the given array elements.


/**
*
* @author Vasanth Raja Chittampally
*/

public class Permutation {

/**
* @param args the command line arguments
*/
void printArray(int []a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");

}
System.out.println("");
}
void permute(int []a,int k ) {
if(k==a.length)
printArray(a);
else
for (int i = k; i < a.length; i++) {
int temp=a[k];
a[k]=a[i];
a[i]=temp;
permute(a,k+1);
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
public static void main(String[] args) {
Permutation p=new Permutation();
int a[]={1,2,3,4,5,6};
p.permute(a, 0);
}

}

Simply edit the array elements(add elements if you want or delete) still it works. I feel the program is self explanatory if you have any doubts please leave a comment.

Advertisements
  1. August 31, 2011 at 10:51 am

    The SJT algorithm would be better.

  2. Soumya
    May 11, 2013 at 7:08 pm

    Your program prints duplicates

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: