rednaZ
0
Q:

permutations of an array

/* to be used something like this:
int [] toBePermuted = new int [] {1, 2, 3, 4};
ArrayList<int[]> a = heap(toBePermuted);
any mention of int [] can be replaced with any other Array of objects */

ArrayList<int []> heap(int [] input) {
  ArrayList<int []> ret = new ArrayList<int []> ();
  ret = generate(input.length, input, ret);
  return ret;
}

ArrayList<int []> generate(int k, int [] a, ArrayList<int []> output) {
  if (k == 1) {
    output.add(a.clone());
  } else {
    output = generate(k-1, a, output);
    for (int i=0; i<k-1; i++) {
      if (k%2 == 0) {
        int temp = a[i];
        a[i] = a[k-1];
        a[k-1] = temp;
      } else {
        int temp = a[0];
        a[0] = a[k-1];
        a[k-1] = temp;
      }
      generate(k-1, a, output);
    }
  }
  return output;
}
1
// Java program to print all permutations using
// Heap's algorithm
class HeapAlgo {
    // Prints the array
    void printArr(int a[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }
 
    // Generating permutation using Heap Algorithm
    void heapPermutation(int a[], int size, int n)
    {
        // if size becomes 1 then prints the obtained
        // permutation
        if (size == 1)
            printArr(a, n);
 
        for (int i = 0; i < size; i++) {
            heapPermutation(a, size - 1, n);
 
            // if size is odd, swap 0th i.e (first) and
            // (size-1)th i.e (last) element
            if (size % 2 == 1) {
                int temp = a[0];
                a[0] = a[size - 1];
                a[size - 1] = temp;
            }
 
            // If size is even, swap ith 
            // and (size-1)th i.e last element
            else {
                int temp = a[i];
                a[i] = a[size - 1];
                a[size - 1] = temp;
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        HeapAlgo obj = new HeapAlgo();
        int a[] = { 1, 2, 3, 4 };
        obj.heapPermutation(a, a.length, a.length);
    }
}
 
// This code has been contributed by Amit Khandelwal.
0

New to Communities?

Join the community