Commit 44b2c2dd authored by Fokion Zervoudakis's avatar Fokion Zervoudakis

Add Algorithm L (next lexicographic permutation).

parent 69d98194
package misc;
import annotation.InPlace;
class AlgorithmL {
/**
Uses Knuth's Algorithm L to generate the next lexicographic permutation of
an element sequence.
<p>Asymptotic analysis:
<ul>
<li>time_worst=O(n)
<li>space_worst=O(1)
</ul>
@param A the target array
*/
@InPlace
void next(int[] A) {
int n = A.length;
int i = n - 2;
while (i >= 0 && A[i] >= A[i + 1]) {
i--;
}
if (i < 0) {
return;
}
int j = n - 1;
while (A[i] >= A[j]) {
j--;
}
swap(A, i, j);
reverse(A, i + 1, n - 1);
}
private void reverse(int[] A, int i, int j) {
while (i < j) {
swap(A, i++, j--);
}
}
private void swap(int[] A, int i, int j) {
int n = A[i];
A[i] = A[j];
A[j] = n;
}
}
package misc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AlgorithmLTest {
private AlgorithmL L;
@BeforeEach
void beforeEach() {
L = new AlgorithmL();
}
@Test
void itFindsTheNextPermutationWithZeroElements() {
var A = new int[0];
L.next(A);
var expected = "[]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithOneElement() {
var A = new int[] { 1 };
L.next(A);
var expected = "[1]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithThreeAscendingElements() {
var A = new int[] { 1, 2, 3 };
L.next(A);
var expected = "[1, 3, 2]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithThreeDescendingElements() {
var A = new int[] { 3, 2, 1 };
L.next(A);
var expected = "[3, 2, 1]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithThreeUnorderedElements() {
var A = new int[] { 1, 3, 2 };
L.next(A);
var expected = "[2, 1, 3]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithManyAscendingElements() {
var A = new int[] { 1, 2, 3, 4, 5 };
L.next(A);
var expected = "[1, 2, 3, 5, 4]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithManyUnorderedElements1() {
var A = new int[] { 1, 2, 3, 5, 4 };
L.next(A);
var expected = "[1, 2, 4, 3, 5]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
@Test
void itFindsTheNextPermutationWithManyUnorderedElements2() {
var A = new int[] { 1, 2, 4, 5, 3 };
L.next(A);
var expected = "[1, 2, 5, 3, 4]";
var actual = Arrays.toString(A);
assertEquals(expected, actual);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment