├── .classpath
├── .gitignore
├── .project
├── .settings
└── org.eclipse.jdt.core.prefs
├── .travis.yml
├── LICENSE
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── build.xml
├── lib
└── junit-4_4.3.1.jar
├── src
└── com
│ └── jwetherell
│ └── algorithms
│ ├── data_structures
│ ├── AVLTree.java
│ ├── BTree.java
│ ├── BinaryHeap.java
│ ├── BinarySearchTree.java
│ ├── CompactSuffixTrie.java
│ ├── DisjointSet.java
│ ├── FenwickTree.java
│ ├── Graph.java
│ ├── HashArrayMappedTrie.java
│ ├── HashMap.java
│ ├── ImplicitKeyTreap.java
│ ├── IntervalSum.java
│ ├── IntervalTree.java
│ ├── KdTree.java
│ ├── LCPArray.java
│ ├── List.java
│ ├── LowestCommonAncestor.java
│ ├── Matrix.java
│ ├── PatriciaTrie.java
│ ├── QuadTree.java
│ ├── Queue.java
│ ├── RadixTrie.java
│ ├── RedBlackTree.java
│ ├── SegmentTree.java
│ ├── SkipList.java
│ ├── SkipListMap.java
│ ├── SplayTree.java
│ ├── Stack.java
│ ├── SuffixArray.java
│ ├── SuffixTree.java
│ ├── SuffixTrie.java
│ ├── TernarySearchTree.java
│ ├── Treap.java
│ ├── TreeMap.java
│ ├── Trie.java
│ ├── TrieMap.java
│ └── interfaces
│ │ ├── IHeap.java
│ │ ├── IList.java
│ │ ├── IMap.java
│ │ ├── IQueue.java
│ │ ├── ISet.java
│ │ ├── IStack.java
│ │ ├── ISuffixTree.java
│ │ └── ITree.java
│ ├── graph
│ ├── AStar.java
│ ├── BellmanFord.java
│ ├── BreadthFirstTraversal.java
│ ├── ConnectedComponents.java
│ ├── CycleDetection.java
│ ├── DepthFirstTraversal.java
│ ├── Dijkstra.java
│ ├── EdmondsKarp.java
│ ├── FloydWarshall.java
│ ├── Johnson.java
│ ├── Kruskal.java
│ ├── Prim.java
│ ├── PushRelabel.java
│ ├── TopologicalSort.java
│ └── TurboMatching.java
│ ├── mathematics
│ ├── Coprimes.java
│ ├── DiscreteLogarithm.java
│ ├── Distance.java
│ ├── Division.java
│ ├── Exponentiation.java
│ ├── FastFourierTransform.java
│ ├── GreatestCommonDivisor.java
│ ├── Knapsack.java
│ ├── LUDecomposition.java
│ ├── Modular.java
│ ├── Multiplication.java
│ ├── Permutations.java
│ ├── Primes.java
│ └── RamerDouglasPeucker.java
│ ├── numbers
│ ├── Complex.java
│ ├── Integers.java
│ └── Longs.java
│ ├── search
│ ├── BinarySearch.java
│ ├── InterpolationSearch.java
│ ├── LinearSearch.java
│ ├── LowerBound.java
│ ├── QuickSelect.java
│ └── UpperBound.java
│ ├── sequence
│ ├── ArithmeticProgression.java
│ ├── FibonacciSequence.java
│ ├── LargestSumContiguousSubarray.java
│ ├── LongestCommonSubsequence.java
│ ├── LongestIncreasingSubsequence.java
│ ├── LongestPalindromicSubsequence.java
│ └── SubsequenceCounter.java
│ ├── sorts
│ ├── AmericanFlagSort.java
│ ├── BubbleSort.java
│ ├── CountingSort.java
│ ├── HeapSort.java
│ ├── InsertionSort.java
│ ├── MergeSort.java
│ ├── QuickSort.java
│ ├── RadixSort.java
│ └── ShellSort.java
│ └── strings
│ ├── KnuthMorrisPratt.java
│ ├── Manacher.java
│ ├── Rotation.java
│ └── StringFunctions.java
└── test
└── com
└── jwetherell
└── algorithms
├── data_structures
├── test
│ ├── AVLTreeTests.java
│ ├── AllTests.java
│ ├── BTreeTests.java
│ ├── BinaryHeapTests.java
│ ├── BinarySearchTreeTests.java
│ ├── CompactSuffixTrieTests.java
│ ├── DisjointSetTests.java
│ ├── FenwickTreeTests.java
│ ├── GraphTests.java
│ ├── HashArrayMappedTreeTests.java
│ ├── HashMapTests.java
│ ├── ImplicitKeyTreapTests.java
│ ├── IntervalSumTest.java
│ ├── IntervalTreeTests.java
│ ├── KdTreeTests.java
│ ├── LCPArrayTest.java
│ ├── ListTests.java
│ ├── LowestCommonAncestorTest.java
│ ├── MatrixTests.java
│ ├── PatriciaTreeTests.java
│ ├── QuadTreeTests.java
│ ├── QueueTests.java
│ ├── RadixTrieTests.java
│ ├── RedBlackTreeTests.java
│ ├── SegmentTreeTests.java
│ ├── SkipListMapTests.java
│ ├── SkipListTests.java
│ ├── SplayTreeTests.java
│ ├── StackTests.java
│ ├── SuffixArrayTest.java
│ ├── SuffixTreeTests.java
│ ├── SuffixTrieTests.java
│ ├── TernarySearchTreeTests.java
│ ├── TreapTests.java
│ ├── TreeMapTests.java
│ ├── TrieMapTests.java
│ ├── TrieTests.java
│ └── common
│ │ ├── HeapTest.java
│ │ ├── IteratorTest.java
│ │ ├── JavaCollectionTest.java
│ │ ├── JavaMapTest.java
│ │ ├── ListIteratorTest.java
│ │ ├── ListTest.java
│ │ ├── MapTest.java
│ │ ├── QueueTest.java
│ │ ├── SetTest.java
│ │ ├── StackTest.java
│ │ ├── SuffixTreeTest.java
│ │ ├── TreeTest.java
│ │ └── Utils.java
└── timing
│ ├── DataStructuresTiming.java
│ └── SpatialDataStructuresTiming.java
├── graph
└── test
│ ├── BreadthFirstTraversalTest.java
│ ├── DepthFirstTraversalTest.java
│ ├── EdmondsKarpTest.java
│ ├── Graphs.java
│ ├── PushRelabelTest.java
│ └── TurboMatchingTest.java
├── mathematics
├── test
│ ├── CoprimesTest.java
│ ├── DiscreteLogarithmTest.java
│ ├── ExponentiationTest.java
│ ├── GCDTest.java
│ ├── LUDecompositionTest.java
│ ├── MathematicsTest.java
│ ├── ModularArithmeticTest.java
│ ├── PermutationsTest.java
│ └── RamerDouglasPeuckerTest.java
└── timing
│ ├── ExponentiationTiming.java
│ ├── GCDTiming.java
│ └── MathematicsTiming.java
├── numbers
├── test
│ └── Numbers.java
└── timing
│ └── NumbersTiming.java
├── search
├── test
│ └── Search.java
└── timing
│ └── SearchTiming.java
├── sequence
├── test
│ └── Sequences.java
└── timing
│ └── SequencesTiming.java
├── sorts
├── test
│ └── Sorts.java
└── timing
│ └── SortsTiming.java
└── strings
├── test
├── KnuthMorrisPrattTests.java
├── ManacherTests.java
├── StringRotation.java
└── Strings.java
└── timing
└── StringsTiming.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 | /build/
3 | /dist/
4 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | JavaAlgorithmsImplementation
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Thu Dec 15 14:40:25 EST 2011
2 | eclipse.preferences.version=1
3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
6 | org.eclipse.jdt.core.compiler.compliance=1.6
7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate
8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate
9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate
10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
12 | org.eclipse.jdt.core.compiler.source=1.6
13 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | before_script:
2 | - sudo apt-get install ant-optional
3 | - export OPTS="-server -Xmx3072M"
4 | - export JAVA_OPTS="${JAVA_OPTS} ${OPTS}"
5 | - export ANT_OPTS="${ANT_OPTS} ${OPTS}"
6 | - echo $JAVA_OPTS
7 | - echo $ANT_OPTS
8 |
9 | dist: trusty
10 |
11 | language: java
12 |
13 | jdk:
14 | - oraclejdk9
15 | - oraclejdk8
16 | # - oraclejdk7
17 | # - oraclejdk6
18 |
19 | # - openjdk9
20 | - openjdk8
21 | - openjdk7
22 | # - openjdk6
23 |
24 | env:
25 | - TEST_SUITE=run_tests
26 | # - TEST_SUITE=mathematics
27 | # - TEST_SUITE=numbers
28 | # - TEST_SUITE=search
29 | # - TEST_SUITE=sequences
30 | # - TEST_SUITE=strings
31 | # - TEST_SUITE=data_structures
32 | # - TEST_SUITE=sorts
33 |
34 | script: "ant $TEST_SUITE"
35 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
8 |
9 |
10 | #### By submitting this pull request I confirm I've read and complied with the below requirements.
11 |
12 | - [ ] I have read the [Contribution guidelines](CONTRIBUTING.md) and I am confident that my PR reflects them.
13 | - [ ] I have followed the [coding guidelines](CONTRIBUTING.md#cs) for this project.
14 | - [ ] My code follows the [skeleton code structure](CONTRIBUTING.md#sample).
15 | - [ ] This pull request has a descriptive title. For example, `Added {Algorithm/DS name} [{Language}]`, not `Update README.md` or `Added new code`.
16 |
--------------------------------------------------------------------------------
/lib/junit-4_4.3.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phishman3579/java-algorithms-implementation/f2d115704691e8e4f6cfe490231d0adb0c3ce7d0/lib/junit-4_4.3.1.jar
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/LCPArray.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * In computer science, the longest common prefix array (LCP array) is an auxiliary
7 | * data structure to the suffix array. It stores the lengths of the longest common
8 | * prefixes (LCPs) between all pairs of consecutive suffixes in a sorted suffix array.
9 | *
10 | * @see LCP Array (Wikipedia)
11 | *
12 | * @author Jakub Szarawarski
13 | * @author Justin Wetherell
14 | */
15 | public class LCPArray {
16 |
17 | private static final char DEFAULT_END_SEQ_CHAR = '$';
18 |
19 | private final char endSeqChar;
20 |
21 | private SuffixArray suffixArray;
22 | private ArrayList lcp;
23 |
24 | public LCPArray(C sequence){
25 | this(sequence, DEFAULT_END_SEQ_CHAR);
26 | }
27 |
28 | public LCPArray(C sequence, char endChar) {
29 | endSeqChar = endChar;
30 | suffixArray = new SuffixArray(sequence, endSeqChar);
31 | }
32 |
33 | public ArrayList getLCPArray() {
34 | if (lcp == null)
35 | LCPAlgorithm();
36 | return lcp;
37 | }
38 |
39 | private void LCPAlgorithm() {
40 | final ArrayList LCPR = getLCPR();
41 | getLCPfromLCPR(LCPR);
42 | }
43 |
44 | private ArrayList getLCPR() {
45 | final ArrayList KMRArrayList = suffixArray.getKMRarray();
46 | final ArrayList suffixArrayList = suffixArray.getSuffixArray();
47 | final String string = suffixArray.getString();
48 | final int length = KMRArrayList.size();
49 | final ArrayList LCPR = new ArrayList(); // helper array, LCP[i] = LCPR[suffixArray[i]]
50 |
51 | int startingValue = 0;
52 | for (int i=0; i 0 ? LCPRValue-1 : 0;
63 | }
64 | }
65 |
66 | return LCPR;
67 | }
68 |
69 | private void getLCPfromLCPR(ArrayList LCPR) {
70 | final ArrayList suffixArrayList = suffixArray.getSuffixArray();
71 | final int length = suffixArrayList.size();
72 |
73 | lcp = new ArrayList();
74 | lcp.add(null); //no value for LCP[0]
75 | for (int i=1; i
11 | * @see Heap (Wikipedia)
12 | *
13 | * @author Justin Wetherell
14 | */
15 | public interface IHeap {
16 |
17 | /**
18 | * Add value to the heap.
19 | *
20 | * @param value to add to the heap.
21 | * @return True if added to the heap.
22 | */
23 | public boolean add(T value);
24 |
25 | /**
26 | * Get the value of the head node from the heap.
27 | *
28 | * @return value of the head node.
29 | */
30 | public T getHeadValue();
31 |
32 | /**
33 | * Remove the head node from the heap.
34 | *
35 | * @return value of the head node.
36 | */
37 | public T removeHead();
38 |
39 | /**
40 | * Remove the value from the heap.
41 | *
42 | * @param value to remove from heap.
43 | * @return True if value was removed form the heap;
44 | */
45 | public T remove(T value);
46 |
47 | /**
48 | * Clear the entire heap.
49 | */
50 | public void clear();
51 |
52 | /**
53 | * Does the value exist in the heap. Warning this is a O(n) operation.
54 | *
55 | * @param value to locate in the heap.
56 | * @return True if the value is in heap.
57 | */
58 | public boolean contains(T value);
59 |
60 | /**
61 | * Get size of the heap.
62 | *
63 | * @return size of the heap.
64 | */
65 | public int size();
66 |
67 | /**
68 | * Validate the heap according to the invariants.
69 | *
70 | * @return True if the heap is valid.
71 | */
72 | public boolean validate();
73 |
74 | /**
75 | * Get this Heap as a Java compatible Collection
76 | *
77 | * @return Java compatible Collection
78 | */
79 | public java.util.Collection toCollection();
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/IList.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * A list or sequence is an abstract data type that implements an ordered
5 | * collection of values, where the same value may occur more than once.
6 | *
7 | * @see List (Wikipedia)
8 | *
9 | * @author Justin Wetherell
10 | */
11 | public interface IList {
12 |
13 | /**
14 | * Add value to list.
15 | *
16 | * @param value to add.
17 | * @return True if added.
18 | */
19 | public boolean add(T value);
20 |
21 | /**
22 | * Remove value from list.
23 | *
24 | * @param value to remove.
25 | * @return True if removed.
26 | */
27 | public boolean remove(T value);
28 |
29 | /**
30 | * Clear the entire list.
31 | */
32 | public void clear();
33 |
34 | /**
35 | * Does the list contain value.
36 | *
37 | * @param value to search list for.
38 | * @return True if list contains value.
39 | */
40 | public boolean contains(T value);
41 |
42 | /**
43 | * Size of the list.
44 | *
45 | * @return size of the list.
46 | */
47 | public int size();
48 |
49 | /**
50 | * Validate the list according to the invariants.
51 | *
52 | * @return True if the list is valid.
53 | */
54 | public boolean validate();
55 |
56 | /**
57 | * Get this List as a Java compatible List
58 | *
59 | * @return Java compatible List
60 | */
61 | public java.util.List toList();
62 |
63 | /**
64 | * Get this List as a Java compatible Collection
65 | *
66 | * @return Java compatible Collection
67 | */
68 | public java.util.Collection toCollection();
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/IMap.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * In computer science, an associative array, map, or dictionary is an abstract
5 | * data type composed of a collection of (key, value) pairs, such that each possible
6 | * key appears at most once in the collection.
7 | *
8 | * @see Associative Array (Wikipedia)
9 | *
10 | * @author Justin Wetherell
11 | */
12 | public interface IMap {
13 |
14 | /**
15 | * Put key->value pair in the map.
16 | *
17 | * @param key to be inserted.
18 | * @param value to be inserted.
19 | * @return V previous value or null if none.
20 | */
21 | public V put(K key, V value);
22 |
23 | /**
24 | * Get value for key.
25 | *
26 | * @param key to get value for.
27 | * @return value mapped to key.
28 | */
29 | public V get(K key);
30 |
31 | /**
32 | * Remove key and value from map.
33 | *
34 | * @param key to remove from the map.
35 | * @return True if removed or False if not found.
36 | */
37 | public V remove(K key);
38 |
39 | /**
40 | * Clear the entire map.
41 | */
42 | public void clear();
43 |
44 | /**
45 | * Does the map contain the key.
46 | *
47 | * @param key to locate in the map.
48 | * @return True if key is in the map.
49 | */
50 | public boolean contains(K key);
51 |
52 | /**
53 | * Number of key/value pairs in the hash map.
54 | *
55 | * @return number of key/value pairs.
56 | */
57 | public int size();
58 |
59 | /**
60 | * Validate the map according to the invariants.
61 | *
62 | * @return True if the map is valid.
63 | */
64 | public boolean validate();
65 |
66 | /**
67 | * Wraps this map in a Java compatible Map
68 | *
69 | * @return Java compatible Map
70 | */
71 | public java.util.Map toMap();
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/IQueue.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * A queue is a particular kind of abstract data type or collection in
5 | * which the entities in the collection are kept in order and the principal (or
6 | * only) operations on the collection are the addition of entities to the rear
7 | * terminal position and removal of entities from the front terminal position.
8 | * This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO
9 | * data structure, the first element added to the queue will be the first one to
10 | * be removed.
11 | *
12 | * @see Queue (Wikipedia)
13 | *
14 | * @author Justin Wetherell
15 | */
16 | public interface IQueue {
17 |
18 | /**
19 | * Add a value to the beginning of the queue.
20 | *
21 | * @param value to add to queue.
22 | * @return True if added to queue.
23 | */
24 | public boolean offer(T value);
25 |
26 | /**
27 | * Remove a value from the tail of the queue.
28 | *
29 | * @return value from the tail of the queue.
30 | */
31 | public T poll();
32 |
33 | /**
34 | * Get but do not remove tail of the queue.
35 | *
36 | * @return value from the tail of the queue.
37 | */
38 | public T peek();
39 |
40 | /**
41 | * Remove the value from the queue.
42 | *
43 | * @param value to remove from the queue.
44 | * @return True if the value was removed from the queue.
45 | */
46 | public boolean remove(T value);
47 |
48 | /**
49 | * Clear the entire queue.
50 | */
51 | public void clear();
52 |
53 | /**
54 | * Does the queue contain the value.
55 | *
56 | * @param value to find in the queue.
57 | * @return True if the queue contains the value.
58 | */
59 | public boolean contains(T value);
60 |
61 | /**
62 | * Get the size of the queue.
63 | *
64 | * @return size of the queue.
65 | */
66 | public int size();
67 |
68 | /**
69 | * Validate the queue according to the invariants.
70 | *
71 | * @return True if the queue is valid.
72 | */
73 | public boolean validate();
74 |
75 | /**
76 | * Get this Queue as a Java compatible Queue
77 | *
78 | * @return Java compatible Queue
79 | */
80 | public java.util.Queue toQueue();
81 |
82 | /**
83 | * Get this Queue as a Java compatible Collection
84 | *
85 | * @return Java compatible Collection
86 | */
87 | public java.util.Collection toCollection();
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/ISet.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * In computer science, a set is an abstract data structure that can store certain values, without
5 | * any particular order, and no repeated values. It is a computer implementation of the mathematical
6 | * concept of a finite set. Unlike most other collection types, rather than retrieving a specific
7 | * element from a set, one typically tests a value for membership in a set.
8 | *
9 | * @see Set (Wikipedia)
10 | *
11 | * @author Justin Wetherell
12 | */
13 | public interface ISet {
14 |
15 | /**
16 | * Add value to set.
17 | *
18 | * @param value to add.
19 | * @return True if added.
20 | */
21 | public boolean add(T value);
22 |
23 | /**
24 | * Remove value from set.
25 | *
26 | * @param value to remove.
27 | * @return True if removed.
28 | */
29 | public boolean remove(T value);
30 |
31 | /**
32 | * Clear the entire set.
33 | */
34 | public void clear();
35 |
36 | /**
37 | * Does the set contain value.
38 | *
39 | * @param value to search set for.
40 | * @return True if set contains value.
41 | */
42 | public boolean contains(T value);
43 |
44 | /**
45 | * Size of the set.
46 | *
47 | * @return size of the set.
48 | */
49 | public int size();
50 |
51 | /**
52 | * Validate the set according to the invariants.
53 | *
54 | * @return True if the set is valid.
55 | */
56 | public boolean validate();
57 |
58 | /**
59 | * Get this Set as a Java compatible Set
60 | *
61 | * @return Java compatible Set
62 | */
63 | public java.util.Set toSet();
64 |
65 | /**
66 | * Get this Set as a Java compatible Collection
67 | *
68 | * @return Java compatible Collection
69 | */
70 | public java.util.Collection toCollection();
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/IStack.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * A stack is a last in, first out (LIFO) abstract data type and linear
5 | * data structure. A stack can have any abstract data type as an element, but is
6 | * characterized by two fundamental operations, called push and pop. The push
7 | * operation adds a new item to the top of the stack, or initializes the stack
8 | * if it is empty. If the stack is full and does not contain enough space to
9 | * accept the given item, the stack is then considered to be in an overflow
10 | * state. The pop operation removes an item from the top of the stack.
11 | *
12 | * @see Stack (Wikipedia)
13 | *
14 | * @author Justin Wetherell
15 | */
16 | public interface IStack {
17 |
18 | /**
19 | * Push value on top of stack
20 | *
21 | * @param value to push on the stack.
22 | */
23 | public boolean push(T value);
24 |
25 | /**
26 | * Pop the value from the top of stack.
27 | *
28 | * @return value popped off the top of the stack.
29 | */
30 | public T pop();
31 |
32 | /**
33 | * Peek the value from the top of stack.
34 | *
35 | * @return value popped off the top of the stack.
36 | */
37 | public T peek();
38 |
39 | /**
40 | * Remove value from stack.
41 | *
42 | * @param value to remove from stack.
43 | * @return True if value was removed.
44 | */
45 | public boolean remove(T value);
46 |
47 | /**
48 | * Clear the entire stack.
49 | */
50 | public void clear();
51 |
52 | /**
53 | * Does stack contain object.
54 | *
55 | * @param value object to find in stack.
56 | * @return True is stack contains object.
57 | */
58 | public boolean contains(T value);
59 |
60 | /**
61 | * Size of the stack.
62 | *
63 | * @return size of the stack.
64 | */
65 | public int size();
66 |
67 | /**
68 | * Validate the stack according to the invariants.
69 | *
70 | * @return True if the stack is valid.
71 | */
72 | public boolean validate();
73 |
74 | /**
75 | * Get this Stack as a Java compatible Queue
76 | *
77 | * @return Java compatible Queue
78 | */
79 | public java.util.Queue toLifoQueue();
80 |
81 | /**
82 | * Get this Stack as a Java compatible Collection
83 | *
84 | * @return Java compatible Collection
85 | */
86 | public java.util.Collection toCollection();
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/ISuffixTree.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | import java.util.Set;
4 |
5 | /**
6 | * In computer science, a suffix tree (also called PAT tree or, in an earlier form, position tree) is a compressed trie
7 | * containing all the suffixes of the given text as their keys and positions in the text as their values. Suffix trees
8 | * allow particularly fast implementations of many important string operations.
9 | *
10 | * @see Suffix Tree (Wikipedia)
11 | *
12 | * @author Justin Wetherell
13 | */
14 | public interface ISuffixTree {
15 |
16 | /**
17 | * Does the sub-sequence exist in the suffix tree.
18 | *
19 | * @param sub-sequence to locate in the tree.
20 | * @return True if the sub-sequence exist in the tree.
21 | */
22 | public boolean doesSubStringExist(C sub);
23 |
24 | /**
25 | * Get all the suffixes in the tree.
26 | *
27 | * @return set of suffixes in the tree.
28 | */
29 | public Set getSuffixes();
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/data_structures/interfaces/ITree.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.data_structures.interfaces;
2 |
3 | /**
4 | * A tree can be defined recursively (locally) as a collection of nodes (starting at a root node),
5 | * where each node is a data structure consisting of a value, together with a list of nodes (the "children"),
6 | * with the constraints that no node is duplicated. A tree can be defined abstractly as a whole (globally)
7 | * as an ordered tree, with a value assigned to each node.
8 | *
9 | * @see Tree (Wikipedia)
10 | *
11 | * @author Justin Wetherell
12 | */
13 | public interface ITree {
14 |
15 | /**
16 | * Add value to the tree. Tree can contain multiple equal values.
17 | *
18 | * @param value to add to the tree.
19 | * @return True if successfully added to tree.
20 | */
21 | public boolean add(T value);
22 |
23 | /**
24 | * Remove first occurrence of value in the tree.
25 | *
26 | * @param value to remove from the tree.
27 | * @return T value removed from tree.
28 | */
29 | public T remove(T value);
30 |
31 | /**
32 | * Clear the entire stack.
33 | */
34 | public void clear();
35 |
36 | /**
37 | * Does the tree contain the value.
38 | *
39 | * @param value to locate in the tree.
40 | * @return True if tree contains value.
41 | */
42 | public boolean contains(T value);
43 |
44 | /**
45 | * Get number of nodes in the tree.
46 | *
47 | * @return Number of nodes in the tree.
48 | */
49 | public int size();
50 |
51 | /**
52 | * Validate the tree according to the invariants.
53 | *
54 | * @return True if the tree is valid.
55 | */
56 | public boolean validate();
57 |
58 | /**
59 | * Get Tree as a Java compatible Collection
60 | *
61 | * @return Java compatible Collection
62 | */
63 | public java.util.Collection toCollection();
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/ConnectedComponents.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | import com.jwetherell.algorithms.data_structures.Graph;
9 | import com.jwetherell.algorithms.data_structures.Graph.Edge;
10 | import com.jwetherell.algorithms.data_structures.Graph.Vertex;
11 |
12 | /**
13 | * In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each
14 | * other by paths, and which is connected to no additional vertices in the supergraph. A vertex with no incident edges is itself a connected
15 | * component. A graph that is itself connected has exactly one connected component, consisting of the whole graph.
16 | *
17 | * @see Connected Components (Wikipedia)
18 | *
19 | * @author Justin Wetherell
20 | */
21 | public class ConnectedComponents {
22 |
23 | private ConnectedComponents() { }
24 |
25 | /**
26 | * Finds the connected components subsets of the Graph.
27 | *
28 | * @param graph
29 | * to find connected components.
30 | * @return List of connected components in the Graph.
31 | */
32 | public static final > List>> getConnectedComponents(Graph graph) {
33 | if (graph == null)
34 | throw new IllegalArgumentException("Graph is NULL.");
35 |
36 | if (graph.getType() != Graph.TYPE.DIRECTED)
37 | throw new IllegalArgumentException("Cannot perform a connected components search on a non-directed graph. graph type = "+graph.getType());
38 |
39 | final Map,Integer> map = new HashMap,Integer>();
40 | final List>> list = new ArrayList>>();
41 |
42 | int c = 0;
43 | for (Vertex v : graph.getVertices())
44 | if (map.get(v) == null)
45 | visit(map, list, v, c++);
46 | return list;
47 | }
48 |
49 | private static final > void visit(Map,Integer> map, List>> list, Vertex v, int c) {
50 | map.put(v, c);
51 |
52 | List> r = null;
53 | if (c == list.size()) {
54 | r = new ArrayList>();
55 | list.add(r);
56 | } else {
57 | r = list.get(c);
58 | }
59 | r.add(v);
60 |
61 | if (v.getEdges().size() > 0) {
62 | boolean found = false;
63 | for (Edge e : v.getEdges()) {
64 | final Vertex to = e.getToVertex();
65 | if (map.get(to) == null) {
66 | visit(map, list, to, c);
67 | found = true;
68 | }
69 | if (found)
70 | break;
71 | }
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/CycleDetection.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import java.util.HashSet;
4 | import java.util.List;
5 | import java.util.Set;
6 |
7 | import com.jwetherell.algorithms.data_structures.Graph;
8 |
9 | /**
10 | * In computer science, cycle detection or cycle finding is the algorithmic problem of finding a cycle in a sequence of iterated function values.
11 | *
12 | * @see Cycle Detection (Wikipedia)
13 | *
14 | * @author Justin Wetherell
15 | */
16 | public class CycleDetection {
17 |
18 | private CycleDetection() { }
19 |
20 | /**
21 | * Cycle detection on a unidrected graph.
22 | *
23 | * @param graph Graph
24 | * @return true if a cycle exists
25 | */
26 | public static > boolean detect(Graph graph) {
27 | if (graph == null)
28 | throw new IllegalArgumentException("Graph is NULL.");
29 |
30 | if (graph.getType() != Graph.TYPE.UNDIRECTED)
31 | throw new IllegalArgumentException("Graph is needs to be Undirected.");
32 |
33 | final Set> visitedVerticies = new HashSet>();
34 | final Set> visitedEdges = new HashSet>();
35 |
36 | final List> verticies = graph.getVertices();
37 | if (verticies == null || verticies.size() == 0)
38 | return false;
39 |
40 | // Select the zero-ith element as the root
41 | final Graph.Vertex root = verticies.get(0);
42 | return depthFirstSearch(root, visitedVerticies, visitedEdges);
43 | }
44 |
45 | private static final > boolean depthFirstSearch(Graph.Vertex vertex, Set> visitedVerticies, Set> visitedEdges) {
46 | if (!visitedVerticies.contains(vertex)) {
47 | // Found an unvisited, add to the set
48 | visitedVerticies.add(vertex);
49 |
50 | final List> edges = vertex.getEdges();
51 | if (edges != null) {
52 | // Follow each unvisited edge, visit the vertex the edge connects to.
53 | for (Graph.Edge edge : edges) {
54 | final Graph.Vertex to = edge.getToVertex();
55 | boolean result = false;
56 | if (to != null && !visitedEdges.contains(edge)) {
57 | visitedEdges.add(edge);
58 |
59 | final Graph.Edge recip = new Graph.Edge(edge.getCost(), edge.getToVertex(), edge.getFromVertex());
60 | visitedEdges.add(recip);
61 |
62 | result = depthFirstSearch(to, visitedVerticies, visitedEdges);
63 | }
64 | if (result == true)
65 | return result;
66 | }
67 | }
68 | } else {
69 | // visited
70 | return true;
71 | }
72 | return false;
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/EdmondsKarp.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 |
4 | import java.util.ArrayDeque;
5 | import java.util.Queue;
6 |
7 | /**
8 | * In computer science, the Edmonds–Karp algorithm is an implementation of the Ford–Fulkerson method for
9 | * computing the maximum flow in a flow network in O(V*E^2) time.
10 | *
11 | * @see Edmonds-Karp Algorithm (Wikipedia)
12 | *
13 | * @author Mateusz Cianciara
14 | * @author Justin Wetherell
15 | */
16 | public class EdmondsKarp {
17 |
18 | private long[][] flow; //max flow beetween i and j verticles
19 | private long[][] capacity; // edge capacity
20 | private int[] parent; //parent
21 | private boolean[] visited; //just for checking if visited
22 | @SuppressWarnings("unused")
23 | private int n, m;
24 |
25 | public EdmondsKarp(int numOfVerticles, int numOfEdges) {
26 | this.n = numOfVerticles;
27 | this.m = numOfEdges;
28 | this.flow = new long[n][n];
29 | this.capacity = new long[n][n];
30 | this.parent = new int[n];
31 | this.visited = new boolean[n];
32 | }
33 |
34 | public void addEdge(int from, int to, long capacity) {
35 | assert capacity >= 0;
36 | this.capacity[from][to] += capacity;
37 | }
38 |
39 | /**
40 | * Get maximum flow.
41 | *
42 | * @param s source
43 | * @param t target
44 | * @return maximum flow
45 | */
46 | public long getMaxFlow(int s, int t) {
47 | while (true) {
48 | final Queue Q = new ArrayDeque();
49 | Q.add(s);
50 |
51 | for (int i = 0; i < this.n; ++i)
52 | visited[i] = false;
53 | visited[s] = true;
54 |
55 | boolean check = false;
56 | int current;
57 | while (!Q.isEmpty()) {
58 | current = Q.peek();
59 | if (current == t) {
60 | check = true;
61 | break;
62 | }
63 | Q.remove();
64 | for (int i = 0; i < n; ++i) {
65 | if (!visited[i] && capacity[current][i] > flow[current][i]) {
66 | visited[i] = true;
67 | Q.add(i);
68 | parent[i] = current;
69 | }
70 | }
71 | }
72 | if (check == false)
73 | break;
74 |
75 | long temp = capacity[parent[t]][t] - flow[parent[t]][t];
76 | for (int i = t; i != s; i = parent[i])
77 | temp = Math.min(temp, (capacity[parent[i]][i] - flow[parent[i]][i]));
78 |
79 | for (int i = t; i != s; i = parent[i]) {
80 | flow[parent[i]][i] += temp;
81 | flow[i][parent[i]] -= temp;
82 | }
83 | }
84 |
85 | long result = 0;
86 | for (int i = 0; i < n; ++i)
87 | result += flow[s][i];
88 | return result;
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/FloydWarshall.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import java.util.HashMap;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | import com.jwetherell.algorithms.data_structures.Graph;
8 |
9 | /**
10 | * Floyd–Warshall algorithm is a graph analysis algorithm for finding shortest
11 | * paths in a weighted graph (with positive or negative edge weights).
12 | *
13 | * Worst case: O(V^3)
14 | *
15 | * @see Floyd-Warshall Algorithm (Wikipedia)
16 | *
17 | * @author Justin Wetherell
18 | */
19 | public class FloydWarshall {
20 |
21 | private FloydWarshall() { }
22 |
23 | public static Map, Map, Integer>> getAllPairsShortestPaths(Graph graph) {
24 | if (graph == null)
25 | throw (new NullPointerException("Graph must be non-NULL."));
26 |
27 | final List> vertices = graph.getVertices();
28 |
29 | final int[][] sums = new int[vertices.size()][vertices.size()];
30 | for (int i = 0; i < sums.length; i++) {
31 | for (int j = 0; j < sums[i].length; j++) {
32 | sums[i][j] = Integer.MAX_VALUE;
33 | }
34 | }
35 |
36 | final List> edges = graph.getEdges();
37 | for (Graph.Edge e : edges) {
38 | final int indexOfFrom = vertices.indexOf(e.getFromVertex());
39 | final int indexOfTo = vertices.indexOf(e.getToVertex());
40 | sums[indexOfFrom][indexOfTo] = e.getCost();
41 | }
42 |
43 | for (int k = 0; k < vertices.size(); k++) {
44 | for (int i = 0; i < vertices.size(); i++) {
45 | for (int j = 0; j < vertices.size(); j++) {
46 | if (i == j) {
47 | sums[i][j] = 0;
48 | } else {
49 | final int ijCost = sums[i][j];
50 | final int ikCost = sums[i][k];
51 | final int kjCost = sums[k][j];
52 | final int summed = (ikCost != Integer.MAX_VALUE &&
53 | kjCost != Integer.MAX_VALUE) ?
54 | (ikCost + kjCost)
55 | :
56 | Integer.MAX_VALUE;
57 | if (ijCost > summed)
58 | sums[i][j] = summed;
59 | }
60 | }
61 | }
62 | }
63 |
64 | final Map, Map, Integer>> allShortestPaths = new HashMap, Map, Integer>>();
65 | for (int i = 0; i < sums.length; i++) {
66 | for (int j = 0; j < sums[i].length; j++) {
67 | final Graph.Vertex from = vertices.get(i);
68 | final Graph.Vertex to = vertices.get(j);
69 |
70 | Map, Integer> map = allShortestPaths.get(from);
71 | if (map == null)
72 | map = new HashMap, Integer>();
73 |
74 | final int cost = sums[i][j];
75 | if (cost != Integer.MAX_VALUE)
76 | map.put(to, cost);
77 | allShortestPaths.put(from, map);
78 | }
79 | }
80 | return allShortestPaths;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/Kruskal.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import com.jwetherell.algorithms.data_structures.Graph;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * Kruskal's minimum spanning tree. Only works on undirected graphs. It finds a
9 | * subset of the edges that forms a tree that includes every vertex, where the
10 | * total weight of all the edges in the tree is minimized.
11 | *
12 | * @see Kruskal's Algorithm (Wikipedia)
13 | *
14 | * @author Bartlomiej Drozd
15 | * @author Justin Wetherell
16 | */
17 | public class Kruskal {
18 |
19 | private Kruskal() { }
20 |
21 | public static Graph.CostPathPair getMinimumSpanningTree(Graph graph) {
22 | if (graph == null)
23 | throw (new NullPointerException("Graph must be non-NULL."));
24 |
25 | // Kruskal's algorithm only works on undirected graphs
26 | if (graph.getType() == Graph.TYPE.DIRECTED)
27 | throw (new IllegalArgumentException("Undirected graphs only."));
28 |
29 | int cost = 0;
30 | final List> path = new ArrayList>();
31 |
32 | // Prepare data to store information which part of tree given vertex is
33 | HashMap, HashSet>> membershipMap = new HashMap, HashSet>>();
34 | for (Graph.Vertex v : graph.getVertices()) {
35 | HashSet> set = new HashSet>();
36 | set.add(v);
37 | membershipMap.put(v, set);
38 | }
39 |
40 | // We make queue of edges to consider all of them, starting with edge with the lowest cost,
41 | // it is important that Edge's class comparator is not natural (ex. sorting is from the biggest to the lowest)
42 | PriorityQueue> edgeQueue = new PriorityQueue>(graph.getEdges());
43 |
44 | while (!edgeQueue.isEmpty()) {
45 | Graph.Edge edge = edgeQueue.poll();
46 |
47 | // If from vertex and to vertex are from different parts of tree then add this edge to result and union vertices' parts
48 | if (!isTheSamePart(edge.getFromVertex(), edge.getToVertex(), membershipMap)) {
49 | union(edge.getFromVertex(), edge.getToVertex(), membershipMap);
50 | path.add(edge);
51 | cost += edge.getCost();
52 | }
53 | }
54 |
55 |
56 | return (new Graph.CostPathPair(cost, path));
57 | }
58 |
59 | private static boolean isTheSamePart(Graph.Vertex v1, Graph.Vertex v2, HashMap, HashSet>> membershipMap) {
60 | return membershipMap.get(v1) == membershipMap.get(v2);
61 | }
62 |
63 | private static void union(Graph.Vertex v1, Graph.Vertex v2, HashMap, HashSet>> membershipMap) {
64 | HashSet> firstSet = membershipMap.get(v1); //first set is the bigger set
65 | HashSet> secondSet = membershipMap.get(v2);
66 |
67 | // we want to include smaller set into bigger, so second set cannot be bigger than first
68 | if (secondSet.size() > firstSet.size()) {
69 | HashSet> tempSet = firstSet;
70 | firstSet = secondSet;
71 | secondSet = tempSet;
72 | }
73 |
74 | // changing part membership of each vertex from smaller set
75 | for (Graph.Vertex v : secondSet) {
76 | membershipMap.put(v, firstSet);
77 | }
78 |
79 | // adding all vertices from smaller set to bigger one
80 | firstSet.addAll(secondSet);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/Prim.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashSet;
5 | import java.util.List;
6 | import java.util.PriorityQueue;
7 | import java.util.Queue;
8 | import java.util.Set;
9 |
10 | import com.jwetherell.algorithms.data_structures.Graph;
11 |
12 | /**
13 | * Prim's minimum spanning tree. Only works on undirected graphs. It finds a
14 | * subset of the edges that forms a tree that includes every vertex, where the
15 | * total weight of all the edges in the tree is minimized.
16 | *
17 | * @see Prim's Minimum Spanning Tree (Wikipedia)
18 | *
19 | * @author Justin Wetherell
20 | */
21 | public class Prim {
22 |
23 | private Prim() { }
24 |
25 | public static Graph.CostPathPair getMinimumSpanningTree(Graph graph, Graph.Vertex start) {
26 | if (graph == null)
27 | throw (new NullPointerException("Graph must be non-NULL."));
28 |
29 | // Prim's algorithm only works on undirected graphs
30 | if (graph.getType() == Graph.TYPE.DIRECTED)
31 | throw (new IllegalArgumentException("Undirected graphs only."));
32 |
33 | int cost = 0;
34 |
35 | final Set> unvisited = new HashSet>();
36 | unvisited.addAll(graph.getVertices());
37 | unvisited.remove(start); // O(1)
38 |
39 | final List> path = new ArrayList>();
40 | final Queue> edgesAvailable = new PriorityQueue>();
41 |
42 | Graph.Vertex vertex = start;
43 | while (!unvisited.isEmpty()) {
44 | // Add all edges to unvisited vertices
45 | for (Graph.Edge e : vertex.getEdges()) {
46 | if (unvisited.contains(e.getToVertex()))
47 | edgesAvailable.add(e);
48 | }
49 |
50 | // Remove the lowest cost edge
51 | final Graph.Edge e = edgesAvailable.remove();
52 | cost += e.getCost();
53 | path.add(e); // O(1)
54 |
55 | vertex = e.getToVertex();
56 | unvisited.remove(vertex); // O(1)
57 | }
58 |
59 | return (new Graph.CostPathPair(cost, path));
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/graph/TopologicalSort.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.graph;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | import com.jwetherell.algorithms.data_structures.Graph;
7 |
8 | /**
9 | * In computer science, a topological sort (sometimes abbreviated topsort or
10 | * toposort) or topological ordering of a directed graph is a linear ordering of
11 | * its vertices such that, for every edge uv, u comes before v in the ordering.
12 | *
13 | * @see Topological Sort (Wikipedia)
14 | *
15 | * @author Justin Wetherell
16 | */
17 | public class TopologicalSort {
18 |
19 | private TopologicalSort() { }
20 |
21 | /**
22 | * Performs a topological sort on a directed graph. Returns NULL if a cycle is detected.
23 | *
24 | * Note: This should NOT change the state of the graph parameter.
25 | *
26 | * @param graph
27 | * @return Sorted List of Vertices or NULL if graph has a cycle
28 | */
29 | public static final List> sort(Graph graph) {
30 | if (graph == null)
31 | throw new IllegalArgumentException("Graph is NULL.");
32 |
33 | if (graph.getType() != Graph.TYPE.DIRECTED)
34 | throw new IllegalArgumentException("Cannot perform a topological sort on a non-directed graph. graph type = "+graph.getType());
35 |
36 | // clone to prevent changes the graph parameter's state
37 | final Graph clone = new Graph(graph);
38 | final List> sorted = new ArrayList>();
39 | final List> noOutgoing = new ArrayList>();
40 |
41 | final List> edges = new ArrayList>();
42 | edges.addAll(clone.getEdges());
43 |
44 | // Find all the vertices which have no outgoing edges
45 | for (Graph.Vertex v : clone.getVertices()) {
46 | if (v.getEdges().size() == 0)
47 | noOutgoing.add(v);
48 | }
49 |
50 | // While we still have vertices which have no outgoing edges
51 | while (noOutgoing.size() > 0) {
52 | final Graph.Vertex current = noOutgoing.remove(0);
53 | sorted.add(current);
54 |
55 | // Go thru each edge, if it goes to the current vertex then remove it.
56 | int i = 0;
57 | while (i < edges.size()) {
58 | final Graph.Edge e = edges.get(i);
59 | final Graph.Vertex from = e.getFromVertex();
60 | final Graph.Vertex to = e.getToVertex();
61 | // Found an edge to the current vertex, remove it.
62 | if (to.equals(current)) {
63 | edges.remove(e);
64 | // Remove the reciprocal edge
65 | from.getEdges().remove(e);
66 | } else {
67 | i++;
68 | }
69 | // Removed all edges from 'from' vertex, add it to the onOutgoing list
70 | if (from.getEdges().size() == 0)
71 | noOutgoing.add(from);
72 | }
73 | }
74 | // If we have processed all connected vertices and there are edges remaining, graph has multiple connected components.
75 | if (edges.size() > 0)
76 | return null;
77 | return sorted;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/Coprimes.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | /**
4 | * In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime (also spelled
5 | * co-prime) if the only positive integer that divides both of them is 1. That is, the only common positive factor
6 | * of the two numbers is 1. This is equivalent to their greatest common divisor being 1.
7 | *
8 | * @see Mutually Prime / Co-prime (Wikipedia)
9 | *
10 | * @author Szymon Stankiewicz
11 | * @author Justin Wetherell
12 | */
13 | public class Coprimes {
14 |
15 | private Coprimes() { }
16 |
17 | /**
18 | *
19 | * Euler's totient function. Because this function is multiplicative such implementation is possible.
20 | *
21 | * Time complexity: O(sqrt(n))
22 | *
23 | * @param n Long integer
24 | * @return number of coprimes smaller or equal to n
25 | */
26 | public static long getNumberOfCoprimes(long n) {
27 | if(n < 1)
28 | return 0;
29 | long res = 1;
30 | for(int i = 2; i*i <= n; i++) {
31 | int times = 0;
32 | while(n%i == 0) {
33 | res *= (times > 0 ? i : i-1);
34 | n /= i;
35 | times++;
36 | }
37 | }
38 | if(n > 1)
39 | res *= n-1;
40 | return res;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/DiscreteLogarithm.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | import java.util.HashMap;
4 |
5 | import static java.lang.Math.sqrt;
6 |
7 | /**
8 | * In mathematics, a discrete logarithm is an integer k exponent solving the equation bk = g, where b and g are
9 | * elements of a group. Discrete logarithms are thus the group-theoretic analogue of ordinary logarithms, which
10 | * solve the same equation for real numbers b and g, where b is the base of the logarithm and g is the value whose
11 | * logarithm is being taken.
12 | *
13 | * @see Discrete Logarithm (Wikipedia)
14 | *
15 | * @author Lucjan Rosłanowski
16 | * @author Justin Wetherell
17 | */
18 | public class DiscreteLogarithm {
19 |
20 | public static final long NO_SOLUTION = -1;
21 |
22 | private static final HashMap set = new HashMap();
23 |
24 | private DiscreteLogarithm() { }
25 |
26 | private static final long pow(long a, long x, long p) {
27 | if (x == 0)
28 | return 1;
29 |
30 | if (x == 1)
31 | return a % p;
32 |
33 | if (x % 2 != 0)
34 | return (a * pow(a, x - 1, p)) % p;
35 |
36 | final long temp = pow(a, x / 2, p) % p;
37 | return (temp * temp) % p;
38 | }
39 |
40 | private static final long getDiscreteLogarithm(HashMap set, long s, long a, long p) {
41 | for (long i = 0; i < s; ++i) {
42 | long el = pow(a, (i * s) % p, p);
43 | el = pow(el, p - 2, p);
44 |
45 | if (set.containsKey(el))
46 | return i * s + set.get(el);
47 | }
48 | return NO_SOLUTION;
49 | }
50 |
51 | private static final void generateSet(long a, long b_1, long p, long s, HashMap set) {
52 | set.clear();
53 | for (long i = 0; i < s; ++i) {
54 | final long first = (pow(a, i, p) * b_1) % p;
55 | if (!set.containsKey(first))
56 | set.put(first, i);
57 | }
58 | }
59 |
60 | /**
61 | * Returns DiscreteLogarithm.NO_SOLUTION when a solution cannot be found
62 | */
63 | public static final long countDiscreteLogarithm(final long a, final long b, final long p) {
64 | final long s = (long) sqrt(p) + 1;
65 | final long b_1 = pow(b, p - 2, p);
66 |
67 | generateSet(a, b_1, p, s, set);
68 | return getDiscreteLogarithm(set, s,a,p);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/Distance.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | public class Distance {
4 |
5 | private Distance() { }
6 |
7 | /*
8 | * Chess distance
9 | */
10 | public static final long chebyshevDistance(long[] point1, long[] point2) {
11 | long x1 = point1[0];
12 | long y1 = point1[1];
13 | long x2 = point2[0];
14 | long y2 = point2[1];
15 | return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2));
16 | }
17 |
18 | public static final double squaredDistance(double x1, double y1, double x2, double y2) {
19 | double x = x1 - x2;
20 | double y = y1 - y2;
21 | double sqr = (x * x) + (y * y);
22 | return sqr;
23 | }
24 |
25 | public static final double euclideanDistance(double x1, double y1, double x2, double y2) {
26 | double x = Math.pow((x1 - x2), 2);
27 | double y = Math.pow((y1 - y2), 2);
28 | double sqrt = Math.sqrt(x + y);
29 | return sqrt;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/Division.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | public class Division {
4 |
5 | public static final long division(int a, int b) {
6 | long result = ((long) a) / ((long) b);
7 | return result;
8 | }
9 |
10 | public static final long divisionUsingLoop(int a, int b) {
11 | int absA = Math.abs(a);
12 | int absB = Math.abs(b);
13 |
14 | long temp = absA;
15 | long result = 0;
16 | while (temp >= 0) {
17 | temp -= absB;
18 | if (temp >= 0)
19 | result++;
20 | }
21 | return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result;
22 | }
23 |
24 | public static final long divisionUsingRecursion(int a, int b) {
25 | int absA = Math.abs(a);
26 | int absB = Math.abs(b);
27 |
28 | long result = 1;
29 | int diff = absA - absB;
30 | if (diff > 0 && diff <= 1) {
31 | return result;
32 | } else if (diff < 0) {
33 | return 0;
34 | }
35 |
36 | result += divisionUsingRecursion(diff, absB);
37 | return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result;
38 | }
39 |
40 | public static final long divisionUsingMultiplication(int a, int b) {
41 | int absA = Math.abs(a);
42 | int absB = Math.abs(b);
43 |
44 | int temp = absB;
45 | int counter = 0;
46 | while (temp <= absA) {
47 | temp = temp << 1;
48 | counter++;
49 | }
50 | absA -= absB << (counter - 1);
51 | long result = (long) Math.pow(2, counter - 1);
52 | if (absB <= absA)
53 | result += divisionUsingMultiplication(absA, absB);
54 | return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result;
55 | }
56 |
57 | public static final long divisionUsingShift(int a, int b) {
58 | int absA = Math.abs(a);
59 | int absB = Math.abs(b);
60 | int tempA, tempB, counter;
61 |
62 | long result = 0L;
63 | while (absA >= absB) {
64 | tempA = absA >> 1; // Right shift "a"
65 | tempB = absB;
66 | counter = 1;
67 | while (tempA >= tempB) { // Double "tempB" until it's larger than
68 | // "tempA"
69 | tempB <<= 1;
70 | counter <<= 1; // Double the counter
71 | }
72 | absA -= tempB; // Subtract "tempB" from "a"
73 | result += counter; // Add counter (2^number of left shifts)
74 | }
75 | return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result;
76 | }
77 |
78 | public static final long divisionUsingLogs(int a, int b) {
79 | long absA = Math.abs(a);
80 | long absB = Math.abs(b);
81 | double logBase10A = Math.log10(absA);
82 | double logBase10B = Math.log10(absB);
83 | double powOf10 = Math.pow(10, (logBase10A - logBase10B));
84 | long result = (long) Math.floor(powOf10);
85 | return (a > 0 && b > 0 || a < 0 && b < 0) ? result : -result;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/Exponentiation.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | /**
4 | * Recursive function of exponentiation is just an implementation of definition.
5 | *
6 | * @see Exponentiation (Wikipedia)
7 | *
8 | * Complexity - O(N) where N is exponent.
9 | *
10 | * Fast exponentiation's complexity is O(lg N)
11 | *
12 | * @see Exponentiation by Squaring (Wikipedia)
13 | *
14 | * Modular exponentiation is similar.
15 | *
16 | * @see Modular Exponentiation (Wikipedia)
17 | *
18 | * This implementation is the fast version of this algorithm with a complexity of O(lg N) also
19 | *
20 | * @author Bartlomiej Drozd
21 | * @author Justin Wetherell
22 | */
23 | public class Exponentiation {
24 |
25 | public static int recursiveExponentiation(int base, int exponent) {
26 | if (exponent == 0)
27 | return 1;
28 | if (exponent == 1)
29 | return base;
30 |
31 | return recursiveExponentiation(base, exponent - 1) * base;
32 | }
33 |
34 | public static int fastRecursiveExponentiation(int base, int exponent) {
35 | if (exponent == 0)
36 | return 1;
37 | if (exponent == 1)
38 | return base;
39 |
40 | final int resultOnHalfExponent = fastRecursiveExponentiation(base, exponent / 2);
41 | if ((exponent % 2) == 0)
42 | return resultOnHalfExponent * resultOnHalfExponent;
43 | else
44 | return resultOnHalfExponent * resultOnHalfExponent * base;
45 |
46 | }
47 |
48 | public static int fastRecursiveExponentiationModulo(int base, int exponent, int mod) {
49 | if (exponent == 0)
50 | return 1;
51 | if (exponent == 1)
52 | return base;
53 |
54 | final int resultOnHalfExponent = fastRecursiveExponentiationModulo(base, exponent / 2, mod);
55 | if ((exponent % 2) == 0)
56 | return (resultOnHalfExponent * resultOnHalfExponent) % mod;
57 | else
58 | return (((resultOnHalfExponent * resultOnHalfExponent) % mod) * base) % mod;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/FastFourierTransform.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | import com.jwetherell.algorithms.numbers.Complex;
4 |
5 | /**
6 | * A fast Fourier transform (FFT) algorithm computes the discrete Fourier transform (DFT) of a sequence, or its inverse.
7 | * Fourier analysis converts a signal from its original domain (often time or space) to a representation in the frequency
8 | * domain and vice versa. An FFT rapidly computes such transformations by factorizing the DFT matrix into a product of
9 | * sparse (mostly zero) factors.
10 | *
11 | * @see Fast Fourier Transform (Wikipedia)
12 | *
13 | * @author Mateusz Cianciara
14 | * @author Justin Wetherell
15 | */
16 | public class FastFourierTransform {
17 |
18 | private FastFourierTransform() { }
19 |
20 | /**
21 | * The Cooley–Tukey algorithm, named after J.W. Cooley and John Tukey, is the most common fast Fourier transform
22 | * (FFT) algorithm. It re-expresses the discrete Fourier transform (DFT) of an arbitrary composite size N = N1N2
23 | * in terms of N1 smaller DFTs of sizes N2, recursively, to reduce the computation time to O(N log N) for highly
24 | * composite N (smooth numbers).
25 | *
26 | * @see Cooley–Tukey Algorithm (Wikipedia)
27 | *
28 | * @param coefficients size must be power of 2
29 | */
30 | public static void cooleyTukeyFFT(Complex[] coefficients) {
31 | final int size = coefficients.length;
32 | if (size <= 1)
33 | return;
34 |
35 | final Complex[] even = new Complex[size / 2];
36 | final Complex[] odd = new Complex[size / 2];
37 | for (int i = 0; i < size; i++) {
38 | if (i % 2 == 0) {
39 | even[i / 2] = coefficients[i];
40 | } else {
41 | odd[(i - 1) / 2] = coefficients[i];
42 | }
43 | }
44 | cooleyTukeyFFT(even);
45 | cooleyTukeyFFT(odd);
46 | for (int k = 0; k < size / 2; k++) {
47 | Complex t = Complex.polar(1.0, -2 * Math.PI * k / size).multiply(odd[k]);
48 | coefficients[k] = even[k].add(t);
49 | coefficients[k + size / 2] = even[k].sub(t);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/GreatestCommonDivisor.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | /**
4 | * In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not
5 | * zero, is the largest positive integer that is a divisor of both numbers.
6 | *
7 | * @see Greatest Common Divisor (Wikipedia)
8 | *
9 | * @author Szymon Stankiewicz
10 | * @author Justin Wetherell
11 | */
12 | public class GreatestCommonDivisor {
13 |
14 | /**
15 | * Calculate greatest common divisor of two numbers using recursion.
16 | *
17 | * Time complexity O(log(a+b))
18 | *
19 | * @param a Long integer
20 | * @param b Long integer
21 | * @return greatest common divisor of a and b
22 | */
23 | public static long gcdUsingRecursion(long a, long b) {
24 | a = Math.abs(a);
25 | b = Math.abs(b);
26 | return a == 0 ? b : gcdUsingRecursion(b%a, a);
27 | }
28 |
29 | /**
30 | * A much more efficient method is the Euclidean algorithm, which uses a division algorithm such as long division
31 | * in combination with the observation that the gcd of two numbers also divides their difference.
32 | *
33 | * @see Euclidean Algorithm (Wikipedia)
34 | */
35 | public static final long gcdUsingEuclides(long x, long y) {
36 | long greater = x;
37 | long smaller = y;
38 | if (y > x) {
39 | greater = y;
40 | smaller = x;
41 | }
42 |
43 | long result = 0;
44 | while (true) {
45 | if (smaller == greater) {
46 | result = smaller; // smaller == greater
47 | break;
48 | }
49 |
50 | greater -= smaller;
51 | if (smaller > greater) {
52 | long temp = smaller;
53 | smaller = greater;
54 | greater = temp;
55 | }
56 | }
57 | return result;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/Knapsack.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a
8 | * collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained
9 | * by a fixed-size knapsack and must fill it with the most valuable items.
10 | *
11 | * @see Knapsack Problem (Wikipedia)
12 | *
13 | * @author Justin Wetherell
14 | */
15 | public class Knapsack {
16 |
17 | public static final int[] zeroOneKnapsack(int[] values, int[] weights, int capacity) {
18 | if (weights.length != values.length)
19 | return null;
20 |
21 | int height = weights.length + 1; // weights==values
22 | int width = capacity + 1;
23 | int[][] output = new int[height][width];
24 | for (int i = 1; i < height; i++) {
25 | int index = i - 1;
26 | for (int j = 1; j < width; j++) {
27 | if (i == 0 || j == 0) {
28 | output[i][j] = 0;
29 | } else {
30 | if (weights[index] > j) {
31 | output[i][j] = output[i - 1][j];
32 | } else {
33 | int v = values[index] + output[i - 1][j - weights[index]];
34 | output[i][j] = Math.max(output[i - 1][j], v);
35 | }
36 | }
37 | }
38 | }
39 |
40 | final List list = new ArrayList();
41 | int i = height - 1;
42 | int j = width - 1;
43 | while (i != 0 && j != 0) {
44 | int current = output[i][j];
45 | int above = output[i - 1][j];
46 | if (current == above) {
47 | i -= 1;
48 | } else {
49 | i -= 1;
50 | j -= weights[i];
51 | list.add(i);
52 | }
53 | }
54 |
55 | int count = 0;
56 | int[] result = new int[list.size()];
57 | for (Object obj : list.toArray()) {
58 | if (obj instanceof Integer)
59 | result[count++] = (Integer) obj;
60 | }
61 |
62 | return result;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/LUDecomposition.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | import com.jwetherell.algorithms.data_structures.Matrix;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 |
9 | /**
10 | * LU decomposition of matrix M produces 2 matrices L and U such that M = L*U
11 | * where L is lower triangular matrix and U is upper triangular matrix
12 | *
13 | * @see LU Decomposition (Wikipedia)
14 | *
15 | * @author Mateusz Cianciara
16 | * @author Justin Wetherell
17 | */
18 | public class LUDecomposition {
19 |
20 | private int n = 0;
21 | private Double[][] L = null;
22 | private Double[][] A = null;
23 | private Integer[] permutation = null;
24 |
25 | public Matrix getL() {
26 | return new Matrix(n, n, L);
27 | }
28 |
29 | public Matrix getU() {
30 | return new Matrix(n, n, A);
31 | }
32 |
33 | public List getPermutation() {
34 | return new ArrayList(Arrays.asList(permutation));
35 | }
36 |
37 | public LUDecomposition(Matrix input) {
38 | if (input.getCols() != input.getRows())
39 | throw new IllegalArgumentException("Matrix is not square");
40 |
41 | n = input.getCols();
42 | L = new Double[n][n];
43 | A = new Double[n][n];
44 | permutation = new Integer[n];
45 |
46 | for (int i = 0; i < n; i++) {
47 | for (int j = 0; j < n; j++) {
48 | L[i][j] = 0.0;
49 | A[i][j] = input.get(i, j);
50 | }
51 | }
52 | for (int i = 0; i < n; i++) {
53 | L[i][i] = 1.0;
54 | permutation[i] = i;
55 | }
56 | for (int row = 0; row < n; row++) {
57 | // find max in column
58 | int max_in_col = row;
59 | double curr_big = Math.abs(A[row][row]);
60 | for (int k = row + 1; k < n; k++) {
61 | if (curr_big < Math.abs(A[k][row])) {
62 | max_in_col = k;
63 | curr_big = Math.abs(A[k][row]);
64 | }
65 | }
66 |
67 | //swap rows
68 | if (row != max_in_col) {
69 | for (int i = 0; i < n; i++) {
70 | double temp = A[row][i];
71 | A[row][i] = A[max_in_col][i];
72 | A[max_in_col][i] = temp;
73 |
74 | if (i < row) {
75 | temp = L[row][i];
76 | L[row][i] = L[max_in_col][i];
77 | L[max_in_col][i] = temp;
78 | }
79 | }
80 | final int temp = permutation[row];
81 | permutation[row] = permutation[max_in_col];
82 | permutation[max_in_col] = temp;
83 | }
84 |
85 | //zero column number row
86 | final double p = A[row][row];
87 | if (p == 0)
88 | return;
89 |
90 | for (int i = row + 1; i < n; i++) {
91 | final double y = A[i][row];
92 | L[i][row] = y / p;
93 |
94 | for (int j = row; j < n; j++) {
95 | A[i][j] -= A[row][j] * (y / p);
96 | }
97 | }
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/mathematics/RamerDouglasPeucker.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.mathematics;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * The Ramer–Douglas–Peucker algorithm (RDP) is an algorithm for reducing the number of points in a
8 | * curve that is approximated by a series of points.
9 | *
10 | * @see Ramer–Douglas–Peucker Algorithm (Wikipedia)
11 | *
12 | * @author Justin Wetherell
13 | */
14 | public class RamerDouglasPeucker {
15 |
16 | private RamerDouglasPeucker() { }
17 |
18 | private static final double sqr(double x) {
19 | return Math.pow(x, 2);
20 | }
21 |
22 | private static final double distanceBetweenPoints(double vx, double vy, double wx, double wy) {
23 | return sqr(vx - wx) + sqr(vy - wy);
24 | }
25 |
26 | private static final double distanceToSegmentSquared(double px, double py, double vx, double vy, double wx, double wy) {
27 | final double l2 = distanceBetweenPoints(vx, vy, wx, wy);
28 | if (l2 == 0)
29 | return distanceBetweenPoints(px, py, vx, vy);
30 | final double t = ((px - vx) * (wx - vx) + (py - vy) * (wy - vy)) / l2;
31 | if (t < 0)
32 | return distanceBetweenPoints(px, py, vx, vy);
33 | if (t > 1)
34 | return distanceBetweenPoints(px, py, wx, wy);
35 | return distanceBetweenPoints(px, py, (vx + t * (wx - vx)), (vy + t * (wy - vy)));
36 | }
37 |
38 | private static final double perpendicularDistance(double px, double py, double vx, double vy, double wx, double wy) {
39 | return Math.sqrt(distanceToSegmentSquared(px, py, vx, vy, wx, wy));
40 | }
41 |
42 | private static final void douglasPeucker(List list, int s, int e, double epsilon, List resultList) {
43 | // Find the point with the maximum distance
44 | double dmax = 0;
45 | int index = 0;
46 |
47 | final int start = s;
48 | final int end = e-1;
49 | for (int i=start+1; i dmax) {
61 | index = i;
62 | dmax = d;
63 | }
64 | }
65 | // If max distance is greater than epsilon, recursively simplify
66 | if (dmax > epsilon) {
67 | // Recursive call
68 | douglasPeucker(list, s, index, epsilon, resultList);
69 | douglasPeucker(list, index, e, epsilon, resultList);
70 | } else {
71 | if ((end-start)>0) {
72 | resultList.add(list.get(start));
73 | resultList.add(list.get(end));
74 | } else {
75 | resultList.add(list.get(start));
76 | }
77 | }
78 | }
79 |
80 | /**
81 | * Given a curve composed of line segments find a similar curve with fewer points.
82 | *
83 | * @param list List of Double[] points (x,y)
84 | * @param epsilon Distance dimension
85 | * @return Similar curve with fewer points
86 | */
87 | public static final List douglasPeucker(List list, double epsilon) {
88 | final List resultList = new ArrayList();
89 | douglasPeucker(list, 0, list.size(), epsilon, resultList);
90 | return resultList;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/numbers/Complex.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.numbers;
2 |
3 | /**
4 | * A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the
5 | * imaginary unit, satisfying the equation i2 = −1.[1] In this expression, a is the real part and b is the imaginary
6 | * part of the complex number. If z=a+bi z=a+bi, then Rz=a, Iz=b.
7 | *
8 | * @see Complex Number (Wikipedia)
9 | *
10 | * @author Mateusz Cianciara
11 | * @author Justin Wetherell
12 | */
13 | public class Complex {
14 |
15 | public double real;
16 | public double imaginary;
17 |
18 | public Complex() {
19 | this.real = 0.0;
20 | this.imaginary = 0.0;
21 | }
22 |
23 | public Complex(double r, double i) {
24 | this.real = r;
25 | this.imaginary = i;
26 | }
27 |
28 | public Complex multiply(final Complex x) {
29 | final Complex copy = new Complex(this.real, this.imaginary);
30 | copy.real = this.real * x.real - this.imaginary * x.imaginary;
31 | copy.imaginary = this.imaginary * x.real + this.real * x.imaginary;
32 | return copy;
33 | }
34 |
35 | public Complex add(final Complex x) {
36 | final Complex copy = new Complex(this.real, this.imaginary);
37 | copy.real += x.real;
38 | copy.imaginary += x.imaginary;
39 | return copy;
40 | }
41 |
42 | public Complex sub(final Complex x) {
43 | final Complex copy = new Complex(this.real, this.imaginary);
44 | copy.real -= x.real;
45 | copy.imaginary -= x.imaginary;
46 | return copy;
47 | }
48 |
49 | public double abs() {
50 | return Math.sqrt(this.real * this.real + this.imaginary * this.imaginary);
51 | }
52 |
53 | public String toString() {
54 | return "(" + this.real + "," + this.imaginary + ")";
55 | }
56 |
57 | public static Complex polar(final double rho, final double theta) {
58 | return (new Complex(rho * Math.cos(theta), rho * Math.sin(theta)));
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/numbers/Longs.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.numbers;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class Longs {
6 |
7 | public static final String toBinaryUsingDivideAndModulus(long numberToConvert) {
8 | long longNumber = numberToConvert;
9 | if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
10 | StringBuilder builder = new StringBuilder();
11 | long temp = 0l;
12 | while (longNumber > 0) {
13 | temp = longNumber;
14 | longNumber = temp / 2;
15 | builder.append(temp % 2);
16 | }
17 | return builder.reverse().toString();
18 | }
19 |
20 | public static final String toBinaryUsingShiftsAndModulus(long numberToConvert) {
21 | long longNumber = numberToConvert;
22 | if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
23 | StringBuilder builder = new StringBuilder();
24 | long temp = 0l;
25 | while (longNumber > 0) {
26 | temp = longNumber;
27 | longNumber = (temp >> 1);
28 | builder.append(temp % 2);
29 | }
30 | return builder.reverse().toString();
31 | }
32 |
33 | public static final String toBinaryUsingBigDecimal(long numberToConvert) {
34 | long longNumber = numberToConvert;
35 | if (longNumber<0) throw new IllegalArgumentException("Method argument cannot be negative. number="+longNumber);
36 | StringBuilder builder = new StringBuilder();
37 | BigDecimal zero = new BigDecimal(0);
38 | BigDecimal two = new BigDecimal(2);
39 | BigDecimal number = new BigDecimal(longNumber);
40 | BigDecimal[] decimals = null;
41 | while (number.compareTo(zero) > 0) {
42 | decimals = number.divideAndRemainder(two);
43 | number = decimals[0];
44 | builder.append(decimals[1]);
45 | }
46 | return builder.reverse().toString();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/BinarySearch.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | /**
4 | * In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. Binary search
5 | * compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is
6 | * successful or the remaining half is empty.
7 | *
8 | * Worst-case performance O(log n)
9 | * Best-case performance O(1)
10 | * Average performance O(log n)
11 | * Worst-case space complexity O(1)
12 | *
13 | * @see Binary Search (Wikipedia)
14 | *
15 | * @author Justin Wetherell
16 | */
17 | public class BinarySearch {
18 |
19 | private static final int SWITCH_TO_BRUTE_FORCE = 200;
20 |
21 | private static int[] sorted = null;
22 |
23 | // Assuming the array is sorted
24 | public static final int find(int value, int[] array, boolean optimize) {
25 | BinarySearch.sorted = array;
26 | try {
27 | return recursiveFind(value, 0, BinarySearch.sorted.length - 1, optimize);
28 | } finally {
29 | BinarySearch.sorted = null;
30 | }
31 | }
32 | //Recursively find the element
33 | //@return find the element value by recursively
34 | private static int recursiveFind(int value, int start, int end, boolean optimize) {
35 | if (start == end) {
36 | int lastValue = sorted[start]; // start==end
37 | if (value == lastValue)
38 | return start; // start==end
39 | return Integer.MAX_VALUE;
40 | }
41 |
42 | final int low = start;
43 | final int high = end + 1; // zero indexed, so add one.
44 | final int middle = low + ((high - low) / 2);
45 |
46 | final int middleValue = sorted[middle];
47 | //checks if the middle index is element
48 | if (value == middleValue)
49 | return middle;
50 | //if value is greater than move to right
51 | if (value > middleValue) {
52 | if (optimize && (end - middle) <= SWITCH_TO_BRUTE_FORCE)
53 | return linearSearch(value, middle + 1, end);
54 | return recursiveFind(value, middle + 1, end, optimize);
55 | }
56 | if (optimize && (end - middle) <= SWITCH_TO_BRUTE_FORCE)
57 | return linearSearch(value, start, middle - 1);
58 | return recursiveFind(value, start, middle - 1, optimize);
59 | }
60 | //Linear search to find the element.
61 | //@value the element we want to find.
62 | //@start first index of the array in the array
63 | //@end last index of the array in the array.
64 | private static final int linearSearch(int value, int start, int end) {
65 | // From index i = start to i = end check if value matches sorted[i]
66 | for (int i = start; i <= end; i++) {
67 | int iValue = sorted[i];
68 | if (value == iValue)
69 | return i;
70 | }
71 | return Integer.MAX_VALUE;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/InterpolationSearch.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | /**
4 | * Interpolation search is an algorithm for searching for a given key in an indexed array that has been ordered by numerical values assigned to the keys (key values). It parallels how humans search
5 | * through a telephone book for a particular name, the key value by which the book's entries are ordered.
6 | *
7 | * Worst-case performance O(n)
8 | * Average performance O(log(log(n)))
9 | *
10 | * @see Interpolation Search (Wikipedia)
11 | *
12 | * @author Justin Wetherell
13 | */
14 | public class InterpolationSearch {
15 |
16 | private static int[] sorted = null;
17 |
18 | // Assuming the array is sorted
19 | public static final int find(int value, int[] array) {
20 | InterpolationSearch.sorted = array;
21 | try {
22 | return recursiveFind(value, 0, InterpolationSearch.sorted.length - 1);
23 | } finally {
24 | InterpolationSearch.sorted = null;
25 | }
26 | }
27 |
28 | private static int recursiveFind(int value, int start, int end) {
29 | if (start == end) {
30 | int lastValue = sorted[start]; // start==end
31 | if (value == lastValue)
32 | return start; // start==end
33 | return Integer.MAX_VALUE;
34 | }
35 |
36 | final int mid = start + ((value - sorted[start]) * (end - start)) / (sorted[end] - sorted[start]);
37 | if (mid < 0 || mid > end)
38 | return Integer.MAX_VALUE;
39 | int midValue = sorted[mid];
40 | if (value == midValue)
41 | return mid;
42 | if (value > midValue)
43 | return recursiveFind(value, mid + 1, end);
44 | return recursiveFind(value, start, mid - 1);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/LinearSearch.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | /**
4 | * In computer science, linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is
5 | * found or until all the elements have been searched.
6 | *
7 | * Worst-case performance O(n)
8 | * Best-case performance O(1)
9 | * Average performance O(n)
10 | * Worst-case space complexity O(1)
11 | *
12 | * @see Linear Search (Wikipedia)
13 | *
14 | * @author Justin Wetherell
15 | */
16 | public class LinearSearch {
17 |
18 | public static final int find(int value, int[] array) {
19 | for (int i = 0; i < array.length; i++) {
20 | int iValue = array[i];
21 | if (value == iValue)
22 | return i;
23 | }
24 | return Integer.MAX_VALUE;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/LowerBound.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | /**
4 | * Lower bound search algorithm.
5 | * Lower bound is kind of binary search algorithm but:
6 | * -If searched element doesn't exist function returns index of first element which is bigger than searched value.
7 | * -If searched element is bigger than any array element function returns first index after last element.
8 | * -If searched element is lower than any array element function returns index of first element.
9 | * -If there are many values equals searched value function returns first occurrence.
10 | * Behaviour for unsorted arrays is unspecified.
11 | *
12 | * Complexity O(log n).
13 | *
14 | * @author Bartlomiej Drozd
15 | * @author Justin Wetherell
16 | */
17 | public class LowerBound {
18 |
19 | private LowerBound() { }
20 |
21 | public static int lowerBound(int[] array, int length, int value) {
22 | int low = 0;
23 | int high = length;
24 | while (low < high) {
25 | final int mid = (low + high) / 2;
26 | //checks if the value is less than middle element of the array
27 | if (value <= array[mid]) {
28 | high = mid;
29 | } else {
30 | low = mid + 1;
31 | }
32 | }
33 | return low;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/QuickSelect.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * In computer science, quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quicksort sorting algorithm.
7 | *
8 | * Worst-case performance О(n2)
9 | * Best-case performance О(n)
10 | * Average performance O(n)
11 | *
12 | * @see Quickselect (Wikipedia)
13 | *
14 | * @author Justin Wetherell
15 | */
16 | public class QuickSelect {
17 |
18 | private static final Random RANDOM = new Random();
19 |
20 | private static int[] unsorted = null;
21 | private static int[] temp = null;
22 |
23 | public static final int find(int value, int[] array) {
24 | unsorted = array;
25 | temp = new int[unsorted.length];
26 | try {
27 | int tempLength = unsorted.length;
28 | int length = tempLength;
29 | int pivot = unsorted[0];
30 | while (length > 0) {
31 | length = tempLength;
32 | pivot = unsorted[RANDOM.nextInt(length)];
33 | tempLength = 0;
34 | for (int i = 0; i < length; i++) {
35 | int iValue = unsorted[i];
36 | if (value == iValue)
37 | return i;
38 | else if (value > pivot && iValue > pivot)
39 | temp[tempLength++] = iValue;
40 | else if (value < pivot && iValue < pivot)
41 | temp[tempLength++] = iValue;
42 | }
43 | unsorted = temp;
44 | length = tempLength;
45 | }
46 | return Integer.MAX_VALUE;
47 | } finally {
48 | QuickSelect.unsorted = null;
49 | QuickSelect.temp = null;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/search/UpperBound.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.search;
2 |
3 | /**
4 | * Upper bound search algorithm.
5 | * Upper bound is kind of binary search algorithm but:
6 | * -It returns index of first element which is grater than searched value.
7 | * -If searched element is bigger than any array element function returns first index after last element.
8 | *
9 | * Behaviour for unsorted arrays is unspecified.
10 | *
11 | * Complexity O(log n).
12 | *
13 | * @author Bartlomiej Drozd
14 | * @author Justin Wetherell
15 | */
16 | public class UpperBound {
17 |
18 | private UpperBound() { }
19 |
20 | public static int upperBound(int[] array, int length, int value) {
21 | int low = 0;
22 | int high = length;
23 | while (low < high) {
24 | final int mid = (low + high) / 2;
25 | if (value >= array[mid]) {
26 | low = mid + 1;
27 | } else {
28 | high = mid;
29 | }
30 | }
31 | return low;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sequence/ArithmeticProgression.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sequence;
2 |
3 | /**
4 | * Compute the result of adding a sequence of numbers from N (startNumber) to N+X (startNumber+numberOfNumbersToCompute)
5 | *
6 | * @see Arithmetic Progression (Wikipedia)
7 | *
8 | * @author Justin Wetherell
9 | */
10 | public class ArithmeticProgression {
11 |
12 | /**
13 | * Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber).
14 | *
15 | * e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X)
16 | */
17 | public static final long sequenceTotalUsingLoop(int startNumber, int numberOfNumbersToCompute) {
18 | int start = startNumber;
19 | int length = numberOfNumbersToCompute;
20 | long result = 0L;
21 | while (length > 0) {
22 | result += start++;
23 | length--;
24 | }
25 | return result;
26 | }
27 |
28 | /**
29 | * Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber) using triangular numbers.
30 | *
31 | * e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X)
32 | *
33 | * @see Triangular Number (Wikipedia)
34 | */
35 | public static final long sequenceTotalUsingTriangularNumbers(int startNumber, int numberOfNumbersToCompute) {
36 | // n*(n+1)/2
37 | final int start = startNumber;
38 | final int length = numberOfNumbersToCompute;
39 |
40 | long result = length * (length + 1) / 2;
41 | result += (start - 1) * length;
42 | return result;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sequence/LargestSumContiguousSubarray.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sequence;
2 |
3 | /**
4 | * Given an array of integers, we want to find the largest sum of contiguous
5 | * subarray.
6 | *
7 | * @see Maximum Subarray Problem (Wikipedia)
8 | *
9 | * @author Miguel Stephane KAKANAKOU
10 | * @author Justin Wetherell
11 | */
12 | public class LargestSumContiguousSubarray {
13 |
14 | private LargestSumContiguousSubarray() { }
15 |
16 | /**
17 | * Largest sum of contiguous subarray using Kadane's algorithm.
18 | *
19 | * @param A
20 | * the given Array of integer
21 | * @return
22 | */
23 | public static int getLargestSumContiguousSubarray(int[] A) {
24 | if (A == null)
25 | throw new NullPointerException("The given array is null");
26 |
27 | int max_so_far = A[0];
28 | int max_ending_here = A[0];
29 | for (int i = 1; i < A.length; i++) {
30 | max_ending_here = Math.max(A[i], max_ending_here + A[i]);
31 | max_so_far = Math.max(max_so_far, max_ending_here);
32 | }
33 | return max_so_far;
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sequence/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sequence;
2 |
3 | /**
4 | * In computer science, the longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in
5 | * which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.
6 | *
7 | * @see Longest Increasing Subsequence Problem (Wikipedia)
8 | *
9 | * @author Bartlomiej Drozd
10 | * @author Justin Wetherell
11 | */
12 | public class LongestIncreasingSubsequence {
13 |
14 | private LongestIncreasingSubsequence() { }
15 |
16 | /**
17 | * Longest increasing subsequence solved using dynamic programming.
18 | */
19 | public static int[] getLongestIncreasingSubsequence(int[] X) {
20 | final int[] P = new int[X.length];
21 | final int[] M = new int[X.length+1];
22 | int L = 0;
23 | for (int i=0; i L) {
43 | // If we found a subsequence longer than any we've found yet, update L
44 | L = newL;
45 | }
46 | }
47 |
48 | // Reconstruct the longest increasing subsequence
49 | final int[] S = new int[L];
50 | int k = M[L];
51 | for (int i=L-1; i>=0; i--) {
52 | S[i] = X[k];
53 | k = P[k];
54 | }
55 |
56 | return S;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sequence/LongestPalindromicSubsequence.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sequence;
2 |
3 | /**
4 | * A longest palindromic subsequence is a sequence that appears in the same
5 | * relative order, but not necessarily contiguous(not substring) and
6 | * palindrome in nature.
7 | *
8 | * Given a string, find the length of the longest palindromic subsequence in it.
9 | *
10 | * @see Longest Palindromic Subsequence (Wikipedia)
11 | *
12 | * @author Miguel Stephane KAKANAKOU
13 | * @author Justin Wetherell
14 | */
15 | public class LongestPalindromicSubsequence {
16 |
17 | private LongestPalindromicSubsequence() { }
18 |
19 | /**
20 | * Find the length of the longest palindromic subsequence in the given
21 | * string s using the dynamic programming approach.
22 | */
23 | public static int getLongestPalindromeSubsequence(String s) {
24 | if (s == null)
25 | throw new NullPointerException("The given String is null");
26 |
27 | final int len = s.length();
28 | final int[][] M = new int[len][len];
29 | final char[] ch = s.toCharArray();
30 |
31 | initializeMatrix(M);
32 | fillMatrix(M, ch);
33 | return M[0][len-1];
34 | }
35 |
36 | private static void initializeMatrix(int[][] M) {
37 | int len = M.length;
38 | for (int i=0; i
6 | * @see Substring occurs in String (GeeksForGeeks)
7 | *
8 | * @author Justin Wetherell
9 | */
10 | public class SubsequenceCounter {
11 |
12 | private static char[] seq = null;
13 | private static char[] subseq = null;
14 | private static int[][] tbl = null;
15 |
16 | private SubsequenceCounter() { }
17 |
18 | /**
19 | * Finds the number of times a string occurs as a subsequence in a text.
20 | *
21 | * @param sequence Text to find subsequence in.
22 | * @param subSequence subsequence to find in the text.
23 | * @return Number of times a string occurs as a subsequence in a text
24 | */
25 | public static int getCount(char[] sequence, char[] subSequence) {
26 | try {
27 | seq = sequence;
28 | subseq = subSequence;
29 | tbl = new int[seq.length + 1][subseq.length + 1];
30 |
31 | for (int row = 0; row < tbl.length; row++)
32 | for (int col = 0; col < tbl[row].length; col++)
33 | tbl[row][col] = countMatches(row, col);
34 |
35 | return tbl[seq.length][subseq.length];
36 | } finally {
37 | seq = null;
38 | subseq = null;
39 | tbl = null;
40 | }
41 | }
42 |
43 | private static int countMatches(int seqDigitsLeft, int subseqDigitsLeft) {
44 | if (subseqDigitsLeft == 0)
45 | return 1;
46 |
47 | if (seqDigitsLeft == 0)
48 | return 0;
49 |
50 | final char currSeqDigit = seq[seq.length - seqDigitsLeft];
51 | final char currSubseqDigit = subseq[subseq.length - subseqDigitsLeft];
52 |
53 | int result = 0;
54 | if (currSeqDigit == currSubseqDigit)
55 | result += tbl[seqDigitsLeft - 1][subseqDigitsLeft - 1];
56 | result += tbl[seqDigitsLeft - 1][subseqDigitsLeft];
57 |
58 | return result;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sorts/AmericanFlagSort.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sorts;
2 |
3 | /**
4 | * An American flag sort is an efficient, in-place variant of radix sort that
5 | * distributes items into hundreds of buckets. Non-comparative sorting
6 | * algorithms such as radix sort and American flag sort are typically used to
7 | * sort large objects such as strings, for which comparison is not a unit-time
8 | * operation.
9 | *
10 | * Family: Bucket.
11 | * Space: In-place.
12 | * Stable: False.
13 | *
14 | * Average case = O(n*k/d)
15 | * Worst case = O(n*k/d)
16 | * Best case = O(n*k/d)
17 | *
18 | * NOTE: n is the number of digits and k is the average bucket size
19 | *
20 | * @see American Flag Sort (Wikipedia)
21 | *
22 | * @author Justin Wetherell
23 | */
24 | public class AmericanFlagSort {
25 |
26 | private static final int NUMBER_OF_BUCKETS = 10; // 10 for base 10 numbers
27 |
28 | private AmericanFlagSort() { }
29 |
30 | public static Integer[] sort(Integer[] unsorted) {
31 | int numberOfDigits = getMaxNumberOfDigits(unsorted); // Max number of digits
32 | int max = 1;
33 | for (int i = 0; i < numberOfDigits - 1; i++)
34 | max *= 10;
35 | sort(unsorted, 0, unsorted.length, max);
36 | return unsorted;
37 | }
38 |
39 | public static void sort(Integer[] unsorted, int start, int length, int divisor) {
40 | // First pass - find counts
41 | int[] count = new int[NUMBER_OF_BUCKETS];
42 | int[] offset = new int[NUMBER_OF_BUCKETS];
43 | int digit = 0;
44 | for (int i = start; i < length; i++) {
45 | int d = unsorted[i];
46 | digit = getDigit(d, divisor);
47 | count[digit]++;
48 | }
49 | offset[0] = start + 0;
50 | for (int i = 1; i < NUMBER_OF_BUCKETS; i++) {
51 | offset[i] = count[i - 1] + offset[i - 1];
52 | }
53 | // Second pass - move into position
54 | for (int b = 0; b < NUMBER_OF_BUCKETS; b++) {
55 | while (count[b] > 0) {
56 | int origin = offset[b];
57 | int from = origin;
58 | int num = unsorted[from];
59 | unsorted[from] = -1;
60 | do {
61 | digit = getDigit(num, divisor);
62 | int to = offset[digit]++;
63 | count[digit]--;
64 | int temp = unsorted[to];
65 | unsorted[to] = num;
66 | num = temp;
67 | from = to;
68 | } while (from != origin);
69 | }
70 | }
71 | if (divisor > 1) {
72 | // Sort the buckets
73 | for (int i = 0; i < NUMBER_OF_BUCKETS; i++) {
74 | int begin = (i > 0) ? offset[i - 1] : start;
75 | int end = offset[i];
76 | if (end - begin > 1)
77 | sort(unsorted, begin, end, divisor / 10);
78 | }
79 | }
80 | }
81 |
82 | private static int getMaxNumberOfDigits(Integer[] unsorted) {
83 | int max = Integer.MIN_VALUE;
84 | int temp = 0;
85 | for (int i : unsorted) {
86 | temp = (int) Math.log10(i) + 1;
87 | if (temp > max)
88 | max = temp;
89 | }
90 | return max;
91 | }
92 |
93 | private static int getDigit(int integer, int divisor) {
94 | return (integer / divisor) % 10;
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sorts/BubbleSort.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sorts;
2 |
3 | /**
4 | * Bubble sort is a simple sorting algorithm that works by repeatedly stepping
5 | * through the list to be sorted, comparing each pair of adjacent items and
6 | * swapping them if they are in the wrong order. The pass through the list is
7 | * repeated until no swaps are needed, which indicates that the list is sorted.
8 | *
9 | * Family: Exchanging.
10 | * Space: In-place.
11 | * Stable: True.
12 | *
13 | * Average case = O(n^2)
14 | * Worst case = O(n^2)
15 | * Best case = O(n)
16 | *
17 | * @see Bubble Sort (Wikipedia)
18 | *
19 | * @author Justin Wetherell
20 | */
21 | public class BubbleSort> {
22 |
23 | private BubbleSort() { }
24 | //@param unsorted array
25 | //@return sorted array
26 | public static > T[] sort(T[] unsorted) {
27 | boolean swapped = true;
28 | int length = unsorted.length;
29 | while (swapped) {
30 | swapped = false;
31 | for (int i = 1; i < length; i++) {
32 | if (unsorted[i].compareTo(unsorted[i - 1]) < 0) {
33 | swap(i, i - 1, unsorted);
34 | swapped = true;
35 | }
36 | }
37 | length--;
38 | }
39 | return unsorted;
40 | }
41 | //swapping the value
42 | private static > void swap(int index1, int index2, T[] unsorted) {
43 | T value = unsorted[index1];
44 | unsorted[index1] = unsorted[index2];
45 | unsorted[index2] = value;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/com/jwetherell/algorithms/sorts/CountingSort.java:
--------------------------------------------------------------------------------
1 | package com.jwetherell.algorithms.sorts;
2 |
3 | /**
4 | * Counting sort is an algorithm for sorting a collection of objects according
5 | * to keys that are small integers; that is, it is an integer sorting algorithm.
6 | * It operates by counting the number of objects that have each distinct key
7 | * value, and using arithmetic on those counts to determine the positions of
8 | * each key value in the output sequence.
9 | *
10 | * Family: Counting.