repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/RabinKarp.java
src/main/java/com/thealgorithms/strings/RabinKarp.java
package com.thealgorithms.strings; import java.util.Scanner; /** * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) * An implementation of Rabin-Karp string matching algorithm Program will simply end if there is no match */ public final class RabinKarp { private RabinKarp() { } public static Scanner scanner = null; public static final int ALPHABET_SIZE = 256; public static void main(String[] args) { scanner = new Scanner(System.in); System.out.println("Enter String"); String text = scanner.nextLine(); System.out.println("Enter pattern"); String pattern = scanner.nextLine(); int q = 101; searchPat(text, pattern, q); } private static void searchPat(String text, String pattern, int q) { int m = pattern.length(); int n = text.length(); int t = 0; int p = 0; int h = 1; int j = 0; int i = 0; h = (int) Math.pow(ALPHABET_SIZE, m - 1) % q; for (i = 0; i < m; i++) { // hash value is calculated for each character and then added with the hash value of the // next character for pattern as well as the text for length equal to the length of // pattern p = (ALPHABET_SIZE * p + pattern.charAt(i)) % q; t = (ALPHABET_SIZE * t + text.charAt(i)) % q; } for (i = 0; i <= n - m; i++) { // if the calculated hash value of the pattern and text matches then // all the characters of the pattern is matched with the text of length equal to length // of the pattern if all matches then pattern exist in string if not then the hash value // of the first character of the text is subtracted and hash value of the next character // after the end of the evaluated characters is added if (p == t) { // if hash value matches then the individual characters are matched for (j = 0; j < m; j++) { // if not matched then break out of the loop if (text.charAt(i + j) != pattern.charAt(j)) { break; } } // if all characters are matched then pattern exist in the string if (j == m) { System.out.println("Pattern found at index " + i); } } // if i<n-m then hash value of the first character of the text is subtracted and hash // value of the next character after the end of the evaluated characters is added to get // the hash value of the next window of characters in the text if (i < n - m) { t = (ALPHABET_SIZE * (t - text.charAt(i) * h) + text.charAt(i + m)) % q; // if hash value becomes less than zero than q is added to make it positive if (t < 0) { t = (t + q); } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/CountChar.java
src/main/java/com/thealgorithms/strings/CountChar.java
package com.thealgorithms.strings; public final class CountChar { private CountChar() { } /** * Counts the number of non-whitespace characters in the given string. * * @param str the input string to count the characters in * @return the number of non-whitespace characters in the specified string; * returns 0 if the input string is null */ public static int countCharacters(String str) { if (str == null) { return 0; } return str.replaceAll("\\s", "").length(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/ReturnSubsequence.java
src/main/java/com/thealgorithms/strings/ReturnSubsequence.java
package com.thealgorithms.strings; /** * Class for generating all subsequences of a given string. */ public final class ReturnSubsequence { private ReturnSubsequence() { } /** * Generates all subsequences of the given string. * * @param input The input string. * @return An array of subsequences. */ public static String[] getSubsequences(String input) { if (input.isEmpty()) { return new String[] {""}; // Return array with an empty string if input is empty } // Recursively find subsequences of the substring (excluding the first character) String[] smallerSubsequences = getSubsequences(input.substring(1)); // Create an array to hold the final subsequences, double the size of smallerSubsequences String[] result = new String[2 * smallerSubsequences.length]; // Copy the smaller subsequences directly to the result array System.arraycopy(smallerSubsequences, 0, result, 0, smallerSubsequences.length); // Prepend the first character of the input string to each of the smaller subsequences for (int i = 0; i < smallerSubsequences.length; i++) { result[i + smallerSubsequences.length] = input.charAt(0) + smallerSubsequences[i]; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java
src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java
package com.thealgorithms.strings; import java.util.HashMap; import java.util.Map; /** * Class for finding the length of the longest substring without repeating characters. */ final class LongestNonRepetitiveSubstring { private LongestNonRepetitiveSubstring() { } /** * Finds the length of the longest substring without repeating characters. * * @param s the input string * @return the length of the longest non-repetitive substring */ public static int lengthOfLongestSubstring(String s) { int maxLength = 0; int start = 0; Map<Character, Integer> charIndexMap = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char currentChar = s.charAt(i); // If the character is already in the map and its index is within the current window if (charIndexMap.containsKey(currentChar) && charIndexMap.get(currentChar) >= start) { // Move the start to the position right after the last occurrence of the current character start = charIndexMap.get(currentChar) + 1; } // Update the last seen index of the current character charIndexMap.put(currentChar, i); // Calculate the maximum length of the substring without repeating characters maxLength = Math.max(maxLength, i - start + 1); } return maxLength; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/PermuteString.java
src/main/java/com/thealgorithms/strings/PermuteString.java
package com.thealgorithms.strings; import java.util.HashSet; import java.util.Set; /** * This class provides methods for generating all permutations of a given string using a backtracking algorithm. * <p> * The algorithm works as follows: * <ol> * <li>Fix a character in the current position and swap it with each of the remaining characters. * For example, for the string "ABC": * <ul> * <li>Fix 'A' at the first position: permutations are "ABC", "BAC", "CBA" (obtained by swapping 'A' with 'B' and 'C' respectively).</li> * </ul> * </li> * <li>Repeat the process for the next character. * For instance, after fixing 'B' in the second position: * <ul> * <li>For "BAC", the permutations include "BAC" and "BCA" (after swapping 'A' and 'C').</li> * </ul> * </li> * <li>After generating permutations for the current position, backtrack by swapping the characters back to their original positions to restore the state. * For example, after generating permutations for "ABC", swap back to restore "BAC" and continue with further permutations.</li> * <li>Repeat the process for all characters to get all possible permutations.</li> * </ol> * </p> */ public final class PermuteString { private PermuteString() { } /** * Generates all possible permutations of the given string. * * <p>This method returns a set containing all unique permutations of the input string. It leverages * a recursive helper method to generate these permutations. * * @param str The input string for which permutations are to be generated. * If the string is null or empty, the result will be an empty set. * @return A {@link Set} of strings containing all unique permutations of the input string. * If the input string has duplicate characters, the set will ensure that only unique permutations * are returned. */ public static Set<String> getPermutations(String str) { Set<String> permutations = new HashSet<>(); generatePermutations(str, 0, str.length(), permutations); return permutations; } /** * Generates all permutations of the given string and collects them into a set. * * @param str the string to permute * @param start the starting index for the current permutation * @param end the end index (length of the string) * @param permutations the set to collect all unique permutations */ private static void generatePermutations(String str, int start, int end, Set<String> permutations) { if (start == end - 1) { permutations.add(str); } else { for (int currentIndex = start; currentIndex < end; currentIndex++) { // Swap the current character with the character at the start index str = swapCharacters(str, start, currentIndex); // Recursively generate permutations for the remaining characters generatePermutations(str, start + 1, end, permutations); // Backtrack: swap the characters back to their original positions str = swapCharacters(str, start, currentIndex); } } } /** * Swaps the characters at the specified positions in the given string. * * @param str the string in which characters will be swapped * @param i the position of the first character to swap * @param j the position of the second character to swap * @return a new string with the characters at positions i and j swapped */ private static String swapCharacters(String str, int i, int j) { char[] chars = str.toCharArray(); char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; return new String(chars); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/ValidParentheses.java
src/main/java/com/thealgorithms/strings/ValidParentheses.java
package com.thealgorithms.strings; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; /** * Validates if a given string has valid matching parentheses. * <p> * A string is considered valid if: * <ul> * <li>Open brackets are closed by the same type of brackets.</li> * <li>Brackets are closed in the correct order.</li> * <li>Every closing bracket has a corresponding open bracket of the same type.</li> * </ul> * * Allowed characters: '(', ')', '{', '}', '[', ']' */ public final class ValidParentheses { private ValidParentheses() { } private static final Map<Character, Character> BRACKET_PAIRS = Map.of(')', '(', '}', '{', ']', '['); /** * Checks if the input string has valid parentheses. * * @param s the string containing only bracket characters * @return true if valid, false otherwise * @throws IllegalArgumentException if the string contains invalid characters or is null */ public static boolean isValid(String s) { if (s == null) { throw new IllegalArgumentException("Input string cannot be null"); } Deque<Character> stack = new ArrayDeque<>(); for (char c : s.toCharArray()) { if (BRACKET_PAIRS.containsValue(c)) { stack.push(c); // opening bracket } else if (BRACKET_PAIRS.containsKey(c)) { if (stack.isEmpty() || stack.pop() != BRACKET_PAIRS.get(c)) { return false; } } else { throw new IllegalArgumentException("Unexpected character: " + c); } } return stack.isEmpty(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/ZAlgorithm.java
src/main/java/com/thealgorithms/strings/ZAlgorithm.java
/* * https://en.wikipedia.org/wiki/Z-algorithm */ package com.thealgorithms.strings; public final class ZAlgorithm { private ZAlgorithm() { throw new UnsupportedOperationException("Utility class"); } public static int[] zFunction(String s) { int n = s.length(); int[] z = new int[n]; int l = 0; int r = 0; for (int i = 1; i < n; i++) { if (i <= r) { z[i] = Math.min(r - i + 1, z[i - l]); } while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) { z[i]++; } if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } public static int search(String text, String pattern) { String s = pattern + "$" + text; int[] z = zFunction(s); int p = pattern.length(); for (int i = 0; i < z.length; i++) { if (z[i] == p) { return i - p - 1; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/LengthOfLastWord.java
src/main/java/com/thealgorithms/strings/LengthOfLastWord.java
package com.thealgorithms.strings; /** * The {@code LengthOfLastWord} class provides a utility method to determine * the length of the last word in a given string. * * <p>A "word" is defined as a maximal substring consisting of non-space * characters only. Trailing spaces at the end of the string are ignored. * * <p><strong>Example:</strong> * <pre>{@code * LengthOfLastWord obj = new LengthOfLastWord(); * System.out.println(obj.lengthOfLastWord("Hello World")); // Output: 5 * System.out.println(obj.lengthOfLastWord(" fly me to the moon ")); // Output: 4 * System.out.println(obj.lengthOfLastWord("luffy is still joyboy")); // Output: 6 * }</pre> * * <p>This implementation runs in O(n) time complexity, where n is the length * of the input string, and uses O(1) additional space. */ public class LengthOfLastWord { /** * Returns the length of the last word in the specified string. * * <p>The method iterates from the end of the string, skipping trailing * spaces first, and then counts the number of consecutive non-space characters * characters until another space (or the beginning of the string) is reached. * * @param s the input string to analyze * @return the length of the last word in {@code s}; returns 0 if there is no word * @throws NullPointerException if {@code s} is {@code null} */ public int lengthOfLastWord(String s) { int sizeOfString = s.length() - 1; int lastWordLength = 0; // Skip trailing spaces from the end of the string while (sizeOfString >= 0 && s.charAt(sizeOfString) == ' ') { sizeOfString--; } // Count the characters of the last word while (sizeOfString >= 0 && s.charAt(sizeOfString) != ' ') { lastWordLength++; sizeOfString--; } return lastWordLength; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/SuffixArray.java
src/main/java/com/thealgorithms/strings/SuffixArray.java
package com.thealgorithms.strings; import java.util.Arrays; /** * Suffix Array implementation in Java. * Builds an array of indices that represent all suffixes of a string in sorted order. * Wikipedia Reference: https://en.wikipedia.org/wiki/Suffix_array * Author: Nithin U. * Github: https://github.com/NithinU2802 */ public final class SuffixArray { private SuffixArray() { } public static int[] buildSuffixArray(String text) { int n = text.length(); Integer[] suffixArray = new Integer[n]; int[] rank = new int[n]; int[] tempRank = new int[n]; // Initial ranking based on characters for (int i = 0; i < n; i++) { suffixArray[i] = i; rank[i] = text.charAt(i); } for (int k = 1; k < n; k *= 2) { final int step = k; // Comparator: first by rank, then by rank + step Arrays.sort(suffixArray, (a, b) -> { if (rank[a] != rank[b]) { return Integer.compare(rank[a], rank[b]); } int ra = (a + step < n) ? rank[a + step] : -1; int rb = (b + step < n) ? rank[b + step] : -1; return Integer.compare(ra, rb); }); // Re-rank tempRank[suffixArray[0]] = 0; for (int i = 1; i < n; i++) { int prev = suffixArray[i - 1]; int curr = suffixArray[i]; boolean sameRank = rank[prev] == rank[curr] && ((prev + step < n ? rank[prev + step] : -1) == (curr + step < n ? rank[curr + step] : -1)); tempRank[curr] = sameRank ? tempRank[prev] : tempRank[prev] + 1; } System.arraycopy(tempRank, 0, rank, 0, n); if (rank[suffixArray[n - 1]] == n - 1) { break; } } return Arrays.stream(suffixArray).mapToInt(Integer::intValue).toArray(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Isomorphic.java
src/main/java/com/thealgorithms/strings/Isomorphic.java
package com.thealgorithms.strings; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Utility class to check if two strings are isomorphic. * * <p> * Two strings {@code s} and {@code t} are isomorphic if the characters in {@code s} * can be replaced to get {@code t}, while preserving the order of characters. * Each character must map to exactly one character, and no two characters can map to the same character. * </p> * * @see <a href="https://en.wikipedia.org/wiki/Isomorphism_(computer_science)">Isomorphic Strings</a> */ public final class Isomorphic { private Isomorphic() { } /** * Checks if two strings are isomorphic. * * @param s the first input string * @param t the second input string * @return {@code true} if {@code s} and {@code t} are isomorphic; {@code false} otherwise */ public static boolean areIsomorphic(String s, String t) { if (s.length() != t.length()) { return false; } Map<Character, Character> map = new HashMap<>(); Set<Character> usedCharacters = new HashSet<>(); for (int i = 0; i < s.length(); i++) { char sourceChar = s.charAt(i); char targetChar = t.charAt(i); if (map.containsKey(sourceChar)) { if (map.get(sourceChar) != targetChar) { return false; } } else { if (usedCharacters.contains(targetChar)) { return false; } map.put(sourceChar, targetChar); usedCharacters.add(targetChar); } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java
src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java
package com.thealgorithms.strings; final class LongestPalindromicSubstring { private LongestPalindromicSubstring() { } /** * Finds the longest palindromic substring in the given string. * * @param s the input string * @return the longest palindromic substring */ public static String longestPalindrome(String s) { if (s == null || s.isEmpty()) { return ""; } String maxStr = ""; for (int i = 0; i < s.length(); ++i) { for (int j = i; j < s.length(); ++j) { if (isValid(s, i, j) && (j - i + 1 > maxStr.length())) { maxStr = s.substring(i, j + 1); } } } return maxStr; } private static boolean isValid(String s, int lo, int hi) { int n = hi - lo + 1; for (int i = 0; i < n / 2; ++i) { if (s.charAt(lo + i) != s.charAt(hi - i)) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Rotation.java
src/main/java/com/thealgorithms/strings/Rotation.java
package com.thealgorithms.strings; /** * Given a string, moving several characters in front of the string to the end * of the string. For example, move the two characters'a' and 'b' in front of * the string "abcdef" to the end of the string, so that the original string * becomes the string "cdefab" */ public final class Rotation { private Rotation() { } public static void main(String[] args) { assert rotation("abcdef", 2).equals("cdefab"); char[] values = "abcdef".toCharArray(); rotation(values, 2); assert new String(values).equals("cdefab"); } /** * Move {@code n} characters in front of given string to the end of string * time complexity: O(n) space complexity: O(n) * * @param s given string * @param n the total characters to be moved * @return string after rotation */ public static String rotation(String s, int n) { return s.substring(n) + s.substring(0, n); } /** * Move {@code n} characters in front of given character array to the end of * array time complexity: O(n) space complexity: O(1) * * @param values given character array * @param n the total characters to be moved */ public static void rotation(char[] values, int n) { reverse(values, 0, n - 1); reverse(values, n, values.length - 1); reverse(values, 0, values.length - 1); } /** * Reverse character array * * @param values character array * @param from begin index of given array * @param to end index of given array */ public static void reverse(char[] values, int from, int to) { while (from < to) { char temp = values[from]; values[from] = values[to]; values[to] = temp; from++; to--; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Upper.java
src/main/java/com/thealgorithms/strings/Upper.java
package com.thealgorithms.strings; public final class Upper { private Upper() { } /** * Driver Code */ public static void main(String[] args) { String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toUpperCase(s).equals(s.toUpperCase()); } } /** * Converts all the characters in this {@code String} to upper case. * * @param s the string to convert * @return the {@code String}, converted to uppercase. */ public static String toUpperCase(String s) { if (s == null) { throw new IllegalArgumentException("Input string cannot be null"); } if (s.isEmpty()) { return s; } StringBuilder result = new StringBuilder(s.length()); for (int i = 0; i < s.length(); ++i) { char currentChar = s.charAt(i); if (Character.isLowerCase(currentChar)) { result.append(Character.toUpperCase(currentChar)); } else { result.append(currentChar); } } return result.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Isogram.java
src/main/java/com/thealgorithms/strings/Isogram.java
package com.thealgorithms.strings; import java.util.HashSet; import java.util.Set; /** * An isogram (also called heterogram or nonpattern word) is a word in which no * letter of the word occurs more than once. Each character appears exactly * once. * * For example, the word "uncopyrightable" is the longest common English isogram * with 15 unique letters. Other examples include "dermatoglyphics" (15 * letters), * "background" (10 letters), "python" (6 letters), and "keyboard" (8 letters). * But words like "hello" and "programming" are not isograms because some * letters * appear multiple times ('l' appears twice in "hello", while 'r', 'm', 'g' * repeat * in "programming"). * * Isograms are particularly valuable in creating substitution ciphers and are * studied in recreational linguistics. A perfect pangram, which uses all 26 * letters * of the alphabet exactly once, is a special type of isogram. * * Reference from https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms */ public final class Isogram { /** * Private constructor to prevent instantiation of utility class. */ private Isogram() { } /** * Checks if a string is an isogram using boolean array approach. * * Time Complexity: O(n) * Space Complexity: O(1) * * @param str the input string * @return true if the string is an isogram, false otherwise * @throws IllegalArgumentException if the string contains non-alphabetic * characters */ public static boolean isAlphabeticIsogram(String str) { if (str == null || str.isEmpty()) { return true; } str = str.toLowerCase(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch < 'a' || ch > 'z') { throw new IllegalArgumentException("Input contains non-alphabetic character: '" + ch + "'"); } } boolean[] seenChars = new boolean[26]; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); int index = ch - 'a'; if (seenChars[index]) { return false; } seenChars[index] = true; } return true; } /** * Checks if a string is an isogram using length comparison approach. * Time Complexity: O(n) * Space Complexity: O(k) where k is the number of unique characters * * @param str the input string * @return true if the string is an isogram, false otherwise */ public static boolean isFullIsogram(String str) { if (str == null || str.isEmpty()) { return true; } str = str.toLowerCase(); Set<Character> uniqueChars = new HashSet<>(); for (char ch : str.toCharArray()) { uniqueChars.add(ch); } return uniqueChars.size() == str.length(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/MyAtoi.java
src/main/java/com/thealgorithms/strings/MyAtoi.java
package com.thealgorithms.strings; /** * A utility class that provides a method to convert a string to a 32-bit signed integer (similar to C/C++'s atoi function). */ public final class MyAtoi { private MyAtoi() { } /** * Converts the given string to a 32-bit signed integer. * The conversion discards any leading whitespace characters until the first non-whitespace character is found. * Then, it takes an optional initial plus or minus sign followed by as many numerical digits as possible and interprets them as a numerical value. * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. * * If the number is out of the range of a 32-bit signed integer: * - Returns {@code Integer.MAX_VALUE} if the value exceeds {@code Integer.MAX_VALUE}. * - Returns {@code Integer.MIN_VALUE} if the value is less than {@code Integer.MIN_VALUE}. * * If no valid conversion could be performed, a zero is returned. * * @param s the string to convert * @return the converted integer, or 0 if the string cannot be converted to a valid integer */ public static int myAtoi(String s) { if (s == null || s.isEmpty()) { return 0; } s = s.trim(); int length = s.length(); if (length == 0) { return 0; } int index = 0; boolean negative = false; // Check for the sign if (s.charAt(index) == '-' || s.charAt(index) == '+') { negative = s.charAt(index) == '-'; index++; } int number = 0; while (index < length) { char ch = s.charAt(index); if (!Character.isDigit(ch)) { break; } int digit = ch - '0'; // Check for overflow if (number > (Integer.MAX_VALUE - digit) / 10) { return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE; } number = number * 10 + digit; index++; } return negative ? -number : number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Lower.java
src/main/java/com/thealgorithms/strings/Lower.java
package com.thealgorithms.strings; public final class Lower { private Lower() { } /** * Driver Code */ public static void main(String[] args) { String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toLowerCase(s).equals(s.toLowerCase()); } } /** * Converts all of the characters in this {@code String} to lower case * * @param s the string to convert * @return the {@code String}, converted to lowercase. */ public static String toLowerCase(String s) { char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { values[i] = Character.toLowerCase(values[i]); } } return new String(values); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/CharactersSame.java
src/main/java/com/thealgorithms/strings/CharactersSame.java
package com.thealgorithms.strings; public final class CharactersSame { private CharactersSame() { } /** * Checks if all characters in the string are the same. * * @param s the string to check * @return {@code true} if all characters in the string are the same or if the string is empty, otherwise {@code false} */ public static boolean isAllCharactersSame(String s) { if (s.isEmpty()) { return true; // Empty strings can be considered as having "all the same characters" } char firstChar = s.charAt(0); for (int i = 1; i < s.length(); i++) { if (s.charAt(i) != firstChar) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/CountWords.java
src/main/java/com/thealgorithms/strings/CountWords.java
package com.thealgorithms.strings; /** * @author Marcus */ public final class CountWords { private CountWords() { } /** * Counts the number of words in the input string. Words are defined as sequences of * characters separated by whitespace. * * @param s the input string * @return the number of words in the input string, or 0 if the string is null or empty */ public static int wordCount(String s) { if (s == null || s.isEmpty()) { return 0; } return s.trim().split("\\s+").length; } /** * Removes all special characters from the input string, leaving only alphanumeric characters * and whitespace. * * @param s the input string * @return a string containing only alphanumeric characters and whitespace */ private static String removeSpecialCharacters(String s) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) { sb.append(c); } } return sb.toString(); } /** * Counts the number of words in a sentence, ignoring all non-alphanumeric characters that do * not contribute to word formation. This method has a time complexity of O(n), where n is the * length of the input string. * * @param s the input string * @return the number of words in the input string, with special characters removed, or 0 if the string is null */ public static int secondaryWordCount(String s) { if (s == null) { return 0; } return wordCount(removeSpecialCharacters(s)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Alphabetical.java
src/main/java/com/thealgorithms/strings/Alphabetical.java
package com.thealgorithms.strings; /** * Utility class for checking if a string's characters are in alphabetical order. * <p> * Alphabetical order is a system whereby character strings are placed in order * based on the position of the characters in the conventional ordering of an * alphabet. * <p> * Reference: <a href="https://en.wikipedia.org/wiki/Alphabetical_order">Wikipedia: Alphabetical Order</a> */ public final class Alphabetical { private Alphabetical() { } /** * Checks whether the characters in the given string are in alphabetical order. * Non-letter characters will cause the check to fail. * * @param s the input string * @return {@code true} if all characters are in alphabetical order (case-insensitive), otherwise {@code false} */ public static boolean isAlphabetical(String s) { s = s.toLowerCase(); for (int i = 0; i < s.length() - 1; ++i) { if (!Character.isLetter(s.charAt(i)) || s.charAt(i) > s.charAt(i + 1)) { return false; } } return !s.isEmpty() && Character.isLetter(s.charAt(s.length() - 1)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/ReverseString.java
src/main/java/com/thealgorithms/strings/ReverseString.java
package com.thealgorithms.strings; import java.util.Stack; /** * Reverse String using different version */ public final class ReverseString { private ReverseString() { } /** * easiest way to reverses the string str and returns it * * @param str string to be reversed * @return reversed string */ public static String reverse(String str) { return new StringBuilder(str).reverse().toString(); } /** * second way to reverses the string str and returns it * * @param str string to be reversed * @return reversed string */ public static String reverse2(String str) { if (str == null || str.isEmpty()) { return str; } char[] value = str.toCharArray(); for (int i = 0, j = str.length() - 1; i < j; i++, j--) { char temp = value[i]; value[i] = value[j]; value[j] = temp; } return new String(value); } /** * Reverse version 3 the given string using a StringBuilder. * This method converts the string to a character array, * iterates through it in reverse order, and appends each character * to a StringBuilder. * * @param string The input string to be reversed. * @return The reversed string. */ public static String reverse3(String string) { if (string.isEmpty()) { return string; } char[] chars = string.toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = string.length() - 1; i >= 0; i--) { sb.append(chars[i]); } return sb.toString(); } /** * Reverses the given string using a stack. * This method uses a stack to reverse the characters of the string. * * @param str The input string to be reversed. * @return The reversed string. */ public static String reverseStringUsingStack(String str) { // Check if the input string is null if (str == null) { throw new IllegalArgumentException("Input string cannot be null"); } Stack<Character> stack = new Stack<>(); StringBuilder reversedString = new StringBuilder(); // Check if the input string is empty if (str.isEmpty()) { return str; } // Push each character of the string onto the stack for (char ch : str.toCharArray()) { stack.push(ch); } // Pop each character from the stack and append to the StringBuilder while (!stack.isEmpty()) { reversedString.append(stack.pop()); } return reversedString.toString(); } /** * Reverse the String using Recursion * @param str string to be reversed * @return reversed string */ public static String reverseStringUsingRecursion(String str) { if (str.isEmpty()) { return str; } else { return reverseStringUsingRecursion(str.substring(1)) + str.charAt(0); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Pangram.java
src/main/java/com/thealgorithms/strings/Pangram.java
package com.thealgorithms.strings; import java.util.HashSet; /** * Wikipedia: https://en.wikipedia.org/wiki/Pangram */ public final class Pangram { private Pangram() { } /** * Test code */ public static void main(String[] args) { assert isPangram("The quick brown fox jumps over the lazy dog"); assert !isPangram("The quick brown fox jumps over the azy dog"); // L is missing assert !isPangram("+-1234 This string is not alphabetical"); assert !isPangram("\u0000/\\"); } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ // alternative approach using Java Collection Framework public static boolean isPangramUsingSet(String s) { HashSet<Character> alpha = new HashSet<>(); s = s.trim().toLowerCase(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != ' ') { alpha.add(s.charAt(i)); } } return alpha.size() == 26; } /** * Checks if a String is considered a Pangram * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram(String s) { boolean[] lettersExisting = new boolean[26]; for (char c : s.toCharArray()) { int letterIndex = c - (Character.isUpperCase(c) ? 'A' : 'a'); if (letterIndex >= 0 && letterIndex < lettersExisting.length) { lettersExisting[letterIndex] = true; } } for (boolean letterFlag : lettersExisting) { if (!letterFlag) { return false; } } return true; } /** * Checks if a String is Pangram or not by checking if each alphabet is present or not * * @param s The String to check * @return {@code true} if s is a Pangram, otherwise {@code false} */ public static boolean isPangram2(String s) { if (s.length() < 26) { return false; } s = s.toLowerCase(); // Converting s to Lower-Case for (char i = 'a'; i <= 'z'; i++) { if (s.indexOf(i) == -1) { return false; // if any alphabet is not present, return false } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
package com.thealgorithms.strings.zigZagPattern; final class ZigZagPattern { private ZigZagPattern() { } /** * Encodes a given string into a zig-zag pattern. * * @param s the input string to be encoded * @param numRows the number of rows in the zigzag pattern * @return the encoded string in zigzag pattern format */ public static String encode(String s, int numRows) { if (numRows < 2 || s.length() < numRows) { return s; } StringBuilder result = new StringBuilder(s.length()); int cycleLength = 2 * numRows - 2; for (int row = 0; row < numRows; row++) { for (int j = row; j < s.length(); j += cycleLength) { result.append(s.charAt(j)); if (row > 0 && row < numRows - 1) { int diagonal = j + cycleLength - 2 * row; if (diagonal < s.length()) { result.append(s.charAt(diagonal)); } } } } return result.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
package com.thealgorithms.audiofilters; /** * N-Order IIR Filter Assumes inputs are normalized to [-1, 1] * * Based on the difference equation from * <a href="https://en.wikipedia.org/wiki/Infinite_impulse_response">Wikipedia link</a> */ public class IIRFilter { private final int order; private final double[] coeffsA; private final double[] coeffsB; private final double[] historyX; private final double[] historyY; /** * Construct an IIR Filter * * @param order the filter's order * @throws IllegalArgumentException if order is zero or less */ public IIRFilter(int order) throws IllegalArgumentException { if (order < 1) { throw new IllegalArgumentException("order must be greater than zero"); } this.order = order; coeffsA = new double[order + 1]; coeffsB = new double[order + 1]; // Sane defaults coeffsA[0] = 1.0; coeffsB[0] = 1.0; historyX = new double[order]; historyY = new double[order]; } /** * Set coefficients * * @param aCoeffs Denominator coefficients * @param bCoeffs Numerator coefficients * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 */ public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { if (aCoeffs.length != order) { throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length); } if (aCoeffs[0] == 0.0) { throw new IllegalArgumentException("aCoeffs.get(0) must not be zero"); } if (bCoeffs.length != order) { throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length); } for (int i = 0; i < order; i++) { coeffsA[i] = aCoeffs[i]; coeffsB[i] = bCoeffs[i]; } } /** * Process a single sample * * @param sample the sample to process * @return the processed sample */ public double process(double sample) { double result = 0.0; // Process for (int i = 1; i <= order; i++) { result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); } result = (result + coeffsB[0] * sample) / coeffsA[0]; // Feedback for (int i = order - 1; i > 0; i--) { historyX[i] = historyX[i - 1]; historyY[i] = historyY[i - 1]; } historyX[0] = sample; historyY[0] = result; return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/audiofilters/EMAFilter.java
src/main/java/com/thealgorithms/audiofilters/EMAFilter.java
package com.thealgorithms.audiofilters; /** * Exponential Moving Average (EMA) Filter for smoothing audio signals. * * <p>This filter applies an exponential moving average to a sequence of audio * signal values, making it useful for smoothing out rapid fluctuations. * The smoothing factor (alpha) controls the degree of smoothing. * * <p>Based on the definition from * <a href="https://en.wikipedia.org/wiki/Moving_average">Wikipedia link</a>. */ public class EMAFilter { private final double alpha; private double emaValue; /** * Constructs an EMA filter with a given smoothing factor. * * @param alpha Smoothing factor (0 < alpha <= 1) * @throws IllegalArgumentException if alpha is not in (0, 1] */ public EMAFilter(double alpha) { if (alpha <= 0 || alpha > 1) { throw new IllegalArgumentException("Alpha must be between 0 and 1."); } this.alpha = alpha; this.emaValue = 0.0; } /** * Applies the EMA filter to an audio signal array. * * @param audioSignal Array of audio samples to process * @return Array of processed (smoothed) samples */ public double[] apply(double[] audioSignal) { if (audioSignal.length == 0) { return new double[0]; } double[] emaSignal = new double[audioSignal.length]; emaValue = audioSignal[0]; emaSignal[0] = emaValue; for (int i = 1; i < audioSignal.length; i++) { emaValue = alpha * audioSignal[i] + (1 - alpha) * emaValue; emaSignal[i] = emaValue; } return emaSignal; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java
src/main/java/com/thealgorithms/ciphers/ADFGVXCipher.java
package com.thealgorithms.ciphers; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * The ADFGVX cipher is a fractionating transposition cipher that was used by * the German Army during World War I. It combines a **Polybius square substitution** * with a **columnar transposition** to enhance encryption strength. * <p> * The name "ADFGVX" refers to the six letters (A, D, F, G, V, X) used as row and * column labels in the Polybius square. This cipher was designed to secure * communication and create complex, hard-to-break ciphertexts. * <p> * Learn more: <a href="https://en.wikipedia.org/wiki/ADFGVX_cipher">ADFGVX Cipher - Wikipedia</a>. * <p> * Example usage: * <pre> * ADFGVXCipher cipher = new ADFGVXCipher(); * String encrypted = cipher.encrypt("attack at 1200am", "PRIVACY"); * String decrypted = cipher.decrypt(encrypted, "PRIVACY"); * </pre> * * @author bennybebo */ public class ADFGVXCipher { // Constants used in the Polybius square private static final char[] POLYBIUS_LETTERS = {'A', 'D', 'F', 'G', 'V', 'X'}; private static final char[][] POLYBIUS_SQUARE = {{'N', 'A', '1', 'C', '3', 'H'}, {'8', 'T', 'B', '2', 'O', 'M'}, {'E', '5', 'W', 'R', 'P', 'D'}, {'4', 'F', '6', 'G', '7', 'I'}, {'9', 'J', '0', 'K', 'L', 'Q'}, {'S', 'U', 'V', 'X', 'Y', 'Z'}}; // Maps for fast substitution lookups private static final Map<String, Character> POLYBIUS_MAP = new HashMap<>(); private static final Map<Character, String> REVERSE_POLYBIUS_MAP = new HashMap<>(); // Static block to initialize the lookup tables from the Polybius square static { for (int i = 0; i < POLYBIUS_SQUARE.length; i++) { for (int j = 0; j < POLYBIUS_SQUARE[i].length; j++) { String key = "" + POLYBIUS_LETTERS[i] + POLYBIUS_LETTERS[j]; POLYBIUS_MAP.put(key, POLYBIUS_SQUARE[i][j]); REVERSE_POLYBIUS_MAP.put(POLYBIUS_SQUARE[i][j], key); } } } /** * Encrypts a given plaintext using the ADFGVX cipher with the provided keyword. * Steps: * 1. Substitute each letter in the plaintext with a pair of ADFGVX letters. * 2. Perform a columnar transposition on the fractionated text using the keyword. * * @param plaintext The message to be encrypted (can contain letters and digits). * @param key The keyword for columnar transposition. * @return The encrypted message as ciphertext. */ public String encrypt(String plaintext, String key) { plaintext = plaintext.toUpperCase().replaceAll("[^A-Z0-9]", ""); // Sanitize input StringBuilder fractionatedText = new StringBuilder(); for (char c : plaintext.toCharArray()) { fractionatedText.append(REVERSE_POLYBIUS_MAP.get(c)); } return columnarTransposition(fractionatedText.toString(), key); } /** * Decrypts a given ciphertext using the ADFGVX cipher with the provided keyword. * Steps: * 1. Reverse the columnar transposition performed during encryption. * 2. Substitute each pair of ADFGVX letters with the corresponding plaintext letter. * The resulting text is the decrypted message. * * @param ciphertext The encrypted message. * @param key The keyword used during encryption. * @return The decrypted plaintext message. */ public String decrypt(String ciphertext, String key) { String fractionatedText = reverseColumnarTransposition(ciphertext, key); StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < fractionatedText.length(); i += 2) { String pair = fractionatedText.substring(i, i + 2); plaintext.append(POLYBIUS_MAP.get(pair)); } return plaintext.toString(); } /** * Helper method: Performs columnar transposition during encryption * * @param text The fractionated text to be transposed * @param key The keyword for columnar transposition * @return The transposed text */ private String columnarTransposition(String text, String key) { int numRows = (int) Math.ceil((double) text.length() / key.length()); char[][] table = new char[numRows][key.length()]; for (char[] row : table) { // Fill empty cells with underscores Arrays.fill(row, '_'); } // Populate the table row by row for (int i = 0; i < text.length(); i++) { table[i / key.length()][i % key.length()] = text.charAt(i); } // Read columns based on the alphabetical order of the key StringBuilder ciphertext = new StringBuilder(); char[] sortedKey = key.toCharArray(); Arrays.sort(sortedKey); for (char keyChar : sortedKey) { int column = key.indexOf(keyChar); for (char[] row : table) { if (row[column] != '_') { ciphertext.append(row[column]); } } } return ciphertext.toString(); } /** * Helper method: Reverses the columnar transposition during decryption * * @param ciphertext The transposed text to be reversed * @param key The keyword used during encryption * @return The reversed text */ private String reverseColumnarTransposition(String ciphertext, String key) { int numRows = (int) Math.ceil((double) ciphertext.length() / key.length()); char[][] table = new char[numRows][key.length()]; char[] sortedKey = key.toCharArray(); Arrays.sort(sortedKey); int index = 0; // Populate the table column by column according to the sorted key for (char keyChar : sortedKey) { int column = key.indexOf(keyChar); for (int row = 0; row < numRows; row++) { if (index < ciphertext.length()) { table[row][column] = ciphertext.charAt(index++); } else { table[row][column] = '_'; } } } // Read the table row by row to reconstruct the fractionated text StringBuilder fractionatedText = new StringBuilder(); for (char[] row : table) { for (char cell : row) { if (cell != '_') { fractionatedText.append(cell); } } } return fractionatedText.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
package com.thealgorithms.ciphers; import java.util.Arrays; /** * The rail fence cipher (also called a zigzag cipher) is a classical type of transposition cipher. * It derives its name from the manner in which encryption is performed, in analogy to a fence built with horizontal rails. * https://en.wikipedia.org/wiki/Rail_fence_cipher * @author https://github.com/Krounosity */ public class RailFenceCipher { // Encrypts the input string using the rail fence cipher method with the given number of rails. public String encrypt(String str, int rails) { // Base case of single rail or rails are more than the number of characters in the string if (rails == 1 || rails >= str.length()) { return str; } // Boolean flag to determine if the movement is downward or upward in the rail matrix. boolean down = true; // Create a 2D array to represent the rails (rows) and the length of the string (columns). char[][] strRail = new char[rails][str.length()]; // Initialize all positions in the rail matrix with a placeholder character ('\n'). for (int i = 0; i < rails; i++) { Arrays.fill(strRail[i], '\n'); } int row = 0; // Start at the first row int col = 0; // Start at the first column int i = 0; // Fill the rail matrix with characters from the string based on the rail pattern. while (col < str.length()) { // Change direction to down when at the first row. if (row == 0) { down = true; } // Change direction to up when at the last row. else if (row == rails - 1) { down = false; } // Place the character in the current position of the rail matrix. strRail[row][col] = str.charAt(i); col++; // Move to the next column. // Move to the next row based on the direction. if (down) { row++; } else { row--; } i++; } // Construct the encrypted string by reading characters row by row. StringBuilder encryptedString = new StringBuilder(); for (char[] chRow : strRail) { for (char ch : chRow) { if (ch != '\n') { encryptedString.append(ch); } } } return encryptedString.toString(); } // Decrypts the input string using the rail fence cipher method with the given number of rails. public String decrypt(String str, int rails) { // Base case of single rail or rails are more than the number of characters in the string if (rails == 1 || rails >= str.length()) { return str; } // Boolean flag to determine if the movement is downward or upward in the rail matrix. boolean down = true; // Create a 2D array to represent the rails (rows) and the length of the string (columns). char[][] strRail = new char[rails][str.length()]; int row = 0; // Start at the first row int col = 0; // Start at the first column // Mark the pattern on the rail matrix using '*'. while (col < str.length()) { // Change direction to down when at the first row. if (row == 0) { down = true; } // Change direction to up when at the last row. else if (row == rails - 1) { down = false; } // Mark the current position in the rail matrix. strRail[row][col] = '*'; col++; // Move to the next column. // Move to the next row based on the direction. if (down) { row++; } else { row--; } } int index = 0; // Index to track characters from the input string. // Fill the rail matrix with characters from the input string based on the marked pattern. for (int i = 0; i < rails; i++) { for (int j = 0; j < str.length(); j++) { if (strRail[i][j] == '*') { strRail[i][j] = str.charAt(index++); } } } // Construct the decrypted string by following the zigzag pattern. StringBuilder decryptedString = new StringBuilder(); row = 0; // Reset to the first row col = 0; // Reset to the first column while (col < str.length()) { // Change direction to down when at the first row. if (row == 0) { down = true; } // Change direction to up when at the last row. else if (row == rails - 1) { down = false; } // Append the character from the rail matrix to the decrypted string. decryptedString.append(strRail[row][col]); col++; // Move to the next column. // Move to the next row based on the direction. if (down) { row++; } else { row--; } } return decryptedString.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/AES.java
src/main/java/com/thealgorithms/ciphers/AES.java
package com.thealgorithms.ciphers; import java.math.BigInteger; import java.util.Scanner; /** * This class is build to demonstrate the application of the AES-algorithm on a * single 128-Bit block of data. */ public final class AES { private AES() { } /** * Precalculated values for x to the power of 2 in Rijndaels galois field. * Used as 'RCON' during the key expansion. */ private static final int[] RCON = { 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, }; /** * Rijndael S-box Substitution table used for encryption in the subBytes * step, as well as the key expansion. */ private static final int[] SBOX = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, }; /** * Inverse Rijndael S-box Substitution table used for decryption in the * subBytesDec step. */ private static final int[] INVERSE_SBOX = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, }; /** * Precalculated lookup table for galois field multiplication by 2 used in * the MixColums step during encryption. */ private static final int[] MULT2 = { 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05, 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5, }; /** * Precalculated lookup table for galois field multiplication by 3 used in * the MixColums step during encryption. */ private static final int[] MULT3 = { 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a, 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a, }; /** * Precalculated lookup table for galois field multiplication by 9 used in * the MixColums step during decryption. */ private static final int[] MULT9 = { 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b, 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46, }; /** * Precalculated lookup table for galois field multiplication by 11 used in * the MixColums step during decryption. */ private static final int[] MULT11 = { 0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e, 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3, }; /** * Precalculated lookup table for galois field multiplication by 13 used in * the MixColums step during decryption. */ private static final int[] MULT13 = { 0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91, 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97, }; /** * Precalculated lookup table for galois field multiplication by 14 used in * the MixColums step during decryption. */ private static final int[] MULT14 = { 0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b, 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1,
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
true
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java
src/main/java/com/thealgorithms/ciphers/AtbashCipher.java
package com.thealgorithms.ciphers; /** * The Atbash cipher is a classic substitution cipher that substitutes each letter * with its opposite letter in the alphabet. * * For example: * - 'A' becomes 'Z', 'B' becomes 'Y', 'C' becomes 'X', and so on. * - Similarly, 'a' becomes 'z', 'b' becomes 'y', and so on. * * The cipher works identically for both uppercase and lowercase letters. * Non-alphabetical characters remain unchanged in the output. * * This cipher is symmetric, meaning that applying the cipher twice will return * the original text. Therefore, the same function is used for both encryption and decryption. * * <p>Usage Example:</p> * <pre> * AtbashCipher cipher = new AtbashCipher("Hello World!"); * String encrypted = cipher.convert(); // Output: "Svool Dliow!" * </pre> * * @author <a href="https://github.com/Krounosity">Krounosity</a> * @see <a href="https://en.wikipedia.org/wiki/Atbash">Atbash Cipher (Wikipedia)</a> */ public class AtbashCipher { private String toConvert; public AtbashCipher() { } /** * Constructor with a string parameter. * * @param str The string to be converted using the Atbash cipher */ public AtbashCipher(String str) { this.toConvert = str; } /** * Returns the current string set for conversion. * * @return The string to be converted */ public String getString() { return toConvert; } /** * Sets the string to be converted using the Atbash cipher. * * @param str The new string to convert */ public void setString(String str) { this.toConvert = str; } /** * Checks if a character is uppercase. * * @param ch The character to check * @return {@code true} if the character is uppercase, {@code false} otherwise */ private boolean isCapital(char ch) { return ch >= 'A' && ch <= 'Z'; } /** * Checks if a character is lowercase. * * @param ch The character to check * @return {@code true} if the character is lowercase, {@code false} otherwise */ private boolean isSmall(char ch) { return ch >= 'a' && ch <= 'z'; } /** * Converts the input string using the Atbash cipher. * Alphabetic characters are substituted with their opposite in the alphabet, * while non-alphabetic characters remain unchanged. * * @return The converted string after applying the Atbash cipher */ public String convert() { StringBuilder convertedString = new StringBuilder(); for (char ch : toConvert.toCharArray()) { if (isSmall(ch)) { convertedString.append((char) ('z' - (ch - 'a'))); } else if (isCapital(ch)) { convertedString.append((char) ('Z' - (ch - 'A'))); } else { convertedString.append(ch); } } return convertedString.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java
src/main/java/com/thealgorithms/ciphers/PermutationCipher.java
package com.thealgorithms.ciphers; import java.util.HashSet; import java.util.Set; /** * A Java implementation of Permutation Cipher. * It is a type of transposition cipher in which the plaintext is divided into blocks * and the characters within each block are rearranged according to a fixed permutation key. * * For example, with key {3, 1, 2} and plaintext "HELLO", the text is divided into blocks * of 3 characters: "HEL" and "LO" (with padding). The characters are then rearranged * according to the key positions. * * @author GitHub Copilot */ public class PermutationCipher { private static final char PADDING_CHAR = 'X'; /** * Encrypts the given plaintext using the permutation cipher with the specified key. * * @param plaintext the text to encrypt * @param key the permutation key (array of integers representing positions) * @return the encrypted text * @throws IllegalArgumentException if the key is invalid */ public String encrypt(String plaintext, int[] key) { validateKey(key); if (plaintext == null || plaintext.isEmpty()) { return plaintext; } // Remove spaces and convert to uppercase for consistent processing String cleanText = plaintext.replaceAll("\\s+", "").toUpperCase(); // Pad the text to make it divisible by key length String paddedText = padText(cleanText, key.length); StringBuilder encrypted = new StringBuilder(); // Process text in blocks of key length for (int i = 0; i < paddedText.length(); i += key.length) { String block = paddedText.substring(i, Math.min(i + key.length, paddedText.length())); encrypted.append(permuteBlock(block, key)); } return encrypted.toString(); } /** * Decrypts the given ciphertext using the permutation cipher with the specified key. * * @param ciphertext the text to decrypt * @param key the permutation key (array of integers representing positions) * @return the decrypted text * @throws IllegalArgumentException if the key is invalid */ public String decrypt(String ciphertext, int[] key) { validateKey(key); if (ciphertext == null || ciphertext.isEmpty()) { return ciphertext; } // Create the inverse permutation int[] inverseKey = createInverseKey(key); StringBuilder decrypted = new StringBuilder(); // Process text in blocks of key length for (int i = 0; i < ciphertext.length(); i += key.length) { String block = ciphertext.substring(i, Math.min(i + key.length, ciphertext.length())); decrypted.append(permuteBlock(block, inverseKey)); } // Remove padding characters from the end return removePadding(decrypted.toString()); } /** * Validates that the permutation key is valid. * A valid key must contain all integers from 1 to n exactly once, where n is the key length. * * @param key the permutation key to validate * @throws IllegalArgumentException if the key is invalid */ private void validateKey(int[] key) { if (key == null || key.length == 0) { throw new IllegalArgumentException("Key cannot be null or empty"); } Set<Integer> keySet = new HashSet<>(); for (int position : key) { if (position < 1 || position > key.length) { throw new IllegalArgumentException("Key must contain integers from 1 to " + key.length); } if (!keySet.add(position)) { throw new IllegalArgumentException("Key must contain each position exactly once"); } } } /** * Pads the text with padding characters to make its length divisible by the block size. * * @param text the text to pad * @param blockSize the size of each block * @return the padded text */ private String padText(String text, int blockSize) { int remainder = text.length() % blockSize; if (remainder == 0) { return text; } int paddingNeeded = blockSize - remainder; StringBuilder padded = new StringBuilder(text); for (int i = 0; i < paddingNeeded; i++) { padded.append(PADDING_CHAR); } return padded.toString(); } /** * Applies the permutation to a single block of text. * * @param block the block to permute * @param key the permutation key * @return the permuted block */ private String permuteBlock(String block, int[] key) { if (block.length() != key.length) { // Handle case where block is shorter than key (shouldn't happen with proper padding) block = padText(block, key.length); } char[] result = new char[key.length]; char[] blockChars = block.toCharArray(); for (int i = 0; i < key.length; i++) { // Key positions are 1-based, so subtract 1 for 0-based array indexing result[i] = blockChars[key[i] - 1]; } return new String(result); } /** * Creates the inverse permutation key for decryption. * * @param key the original permutation key * @return the inverse key */ private int[] createInverseKey(int[] key) { int[] inverse = new int[key.length]; for (int i = 0; i < key.length; i++) { // The inverse key maps each position to where it should go inverse[key[i] - 1] = i + 1; } return inverse; } /** * Removes padding characters from the end of the decrypted text. * * @param text the text to remove padding from * @return the text without padding */ private String removePadding(String text) { if (text.isEmpty()) { return text; } int i = text.length() - 1; while (i >= 0 && text.charAt(i) == PADDING_CHAR) { i--; } return text.substring(0, i + 1); } /** * Gets the padding character used by this cipher. * * @return the padding character */ public char getPaddingChar() { return PADDING_CHAR; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
src/main/java/com/thealgorithms/ciphers/ProductCipher.java
package com.thealgorithms.ciphers; import java.util.Scanner; final class ProductCipher { private ProductCipher() { } public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter the input to be encrypted: "); String substitutionInput = sc.nextLine(); System.out.println(" "); System.out.println("Enter a number: "); int n = sc.nextInt(); // Substitution encryption StringBuffer substitutionOutput = new StringBuffer(); for (int i = 0; i < substitutionInput.length(); i++) { char c = substitutionInput.charAt(i); substitutionOutput.append((char) (c + 5)); } System.out.println(" "); System.out.println("Substituted text: "); System.out.println(substitutionOutput); // Transposition encryption String transpositionInput = substitutionOutput.toString(); int modulus = transpositionInput.length() % n; if (modulus != 0) { modulus = n - modulus; for (; modulus != 0; modulus--) { transpositionInput += "/"; } } StringBuffer transpositionOutput = new StringBuffer(); System.out.println(" "); System.out.println("Transposition Matrix: "); for (int i = 0; i < n; i++) { for (int j = 0; j < transpositionInput.length() / n; j++) { char c = transpositionInput.charAt(i + (j * n)); System.out.print(c); transpositionOutput.append(c); } System.out.println(); } System.out.println(" "); System.out.println("Final encrypted text: "); System.out.println(transpositionOutput); // Transposition decryption n = transpositionOutput.length() / n; StringBuffer transpositionPlaintext = new StringBuffer(); for (int i = 0; i < n; i++) { for (int j = 0; j < transpositionOutput.length() / n; j++) { char c = transpositionOutput.charAt(i + (j * n)); transpositionPlaintext.append(c); } } // Substitution decryption StringBuffer plaintext = new StringBuffer(); for (int i = 0; i < transpositionPlaintext.length(); i++) { char c = transpositionPlaintext.charAt(i); plaintext.append((char) (c - 5)); } System.out.println("Plaintext: "); System.out.println(plaintext); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/Autokey.java
src/main/java/com/thealgorithms/ciphers/Autokey.java
package com.thealgorithms.ciphers; /** * The Autokey Cipher is an interesting and historically significant encryption method, * as it improves upon the classic Vigenère Cipher by using the plaintext itself to * extend the key. This makes it harder to break using frequency analysis, as it * doesn’t rely solely on a repeated key. * https://en.wikipedia.org/wiki/Autokey_cipher * * @author bennybebo */ public class Autokey { // Encrypts the plaintext using the Autokey cipher public String encrypt(String plaintext, String keyword) { plaintext = plaintext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input keyword = keyword.toUpperCase(); StringBuilder extendedKey = new StringBuilder(keyword); extendedKey.append(plaintext); // Extend key with plaintext StringBuilder ciphertext = new StringBuilder(); for (int i = 0; i < plaintext.length(); i++) { char plainChar = plaintext.charAt(i); char keyChar = extendedKey.charAt(i); int encryptedChar = (plainChar - 'A' + keyChar - 'A') % 26 + 'A'; ciphertext.append((char) encryptedChar); } return ciphertext.toString(); } // Decrypts the ciphertext using the Autokey cipher public String decrypt(String ciphertext, String keyword) { ciphertext = ciphertext.toUpperCase().replaceAll("[^A-Z]", ""); // Sanitize input keyword = keyword.toUpperCase(); StringBuilder plaintext = new StringBuilder(); StringBuilder extendedKey = new StringBuilder(keyword); for (int i = 0; i < ciphertext.length(); i++) { char cipherChar = ciphertext.charAt(i); char keyChar = extendedKey.charAt(i); int decryptedChar = (cipherChar - 'A' - (keyChar - 'A') + 26) % 26 + 'A'; plaintext.append((char) decryptedChar); extendedKey.append((char) decryptedChar); // Extend key with each decrypted char } return plaintext.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/Vigenere.java
src/main/java/com/thealgorithms/ciphers/Vigenere.java
package com.thealgorithms.ciphers; /** * A Java implementation of the Vigenère Cipher. * * The Vigenère Cipher is a polyalphabetic substitution cipher that uses a * keyword to shift letters in the plaintext by different amounts, depending * on the corresponding character in the keyword. It wraps around the alphabet, * ensuring the shifts are within 'A'-'Z' or 'a'-'z'. * * Non-alphabetic characters (like spaces, punctuation) are kept unchanged. * * Encryption Example: * - Plaintext: "Hello World!" * - Key: "suchsecret" * - Encrypted Text: "Zynsg Yfvev!" * * Decryption Example: * - Ciphertext: "Zynsg Yfvev!" * - Key: "suchsecret" * - Decrypted Text: "Hello World!" * * Wikipedia Reference: * <a href="https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher">Vigenère Cipher - Wikipedia</a> * * @author straiffix * @author beingmartinbmc */ public class Vigenere { /** * Encrypts a given message using the Vigenère Cipher with the specified key. * Steps: * 1. Iterate over each character in the message. * 2. If the character is a letter, shift it by the corresponding character in the key. * 3. Preserve the case of the letter. * 4. Preserve non-alphabetic characters. * 5. Move to the next character in the key (cyclic). * 6. Return the encrypted message. * * @param message The plaintext message to encrypt. * @param key The keyword used for encryption. * @throws IllegalArgumentException if the key is empty. * @return The encrypted message. */ public String encrypt(final String message, final String key) { if (key.isEmpty()) { throw new IllegalArgumentException("Key cannot be empty."); } StringBuilder result = new StringBuilder(); int j = 0; for (int i = 0; i < message.length(); i++) { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); } else { result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); } j = ++j % key.length(); } else { result.append(c); } } return result.toString(); } /** * Decrypts a given message encrypted with the Vigenère Cipher using the specified key. * Steps: * 1. Iterate over each character in the message. * 2. If the character is a letter, shift it back by the corresponding character in the key. * 3. Preserve the case of the letter. * 4. Preserve non-alphabetic characters. * 5. Move to the next character in the key (cyclic). * 6. Return the decrypted message. * * @param message The encrypted message to decrypt. * @param key The keyword used for decryption. * @throws IllegalArgumentException if the key is empty. * @return The decrypted plaintext message. */ public String decrypt(final String message, final String key) { if (key.isEmpty()) { throw new IllegalArgumentException("Key cannot be empty."); } StringBuilder result = new StringBuilder(); int j = 0; for (int i = 0; i < message.length(); i++) { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); } else { result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); } j = ++j % key.length(); } else { result.append(c); } } return result.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/Blowfish.java
src/main/java/com/thealgorithms/ciphers/Blowfish.java
package com.thealgorithms.ciphers; /* * Java program for Blowfish Algorithm * Wikipedia: https://en.wikipedia.org/wiki/Blowfish_(cipher) * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public class Blowfish { // Initializing substitution boxes String[][] sBox = { { "d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed", "6a267e96", "ba7c9045", "f12c7f99", "24a19947", "b3916cf7", "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3", "f4933d7e", "0d95748f", "728eb658", "718bcd58", "82154aee", "7b54a41d", "c25a59b5", "9c30d539", "2af26013", "c5d1b023", "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e", "6c9e0e8b", "b01e8a3e", "d71577c1", "bd314b27", "78af2fda", "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440", "55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af", "7c72e993", "b3ee1411", "636fbc2a", "2ba9c55d", "741831f6", "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381", "28958677", "3b8f4898", "6b4bb9af", "c4bfe81b", "66282193", "61d809cc", "fb21a991", "487cac60", "5dec8032", "ef845d5d", "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5", "0f6d6ff3", "83f44239", "2e0b4482", "a4842004", "69c8f04a", "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0", "6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c", "137a3be4", "ba3bf050", "7efb2a98", "a1f1651d", "39af0176", "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3", "3b8b5ebe", "e06f75d8", "85c12073", "401a449f", "56c16aa6", "4ed3aa62", "363f7706", "1bfedf72", "429b023d", "37d0d724", "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b", "25d479d8", "f6e8def7", "e3fe501a", "b6794c3b", "976ce0bd", "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463", "68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f", "9b30952c", "cc814544", "af5ebd09", "bee3d004", "de334afd", "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39", "b9d3fbdb", "5579c0bd", "1a60320a", "d6a100c6", "402c7279", "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8", "3c7516df", "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760", "53317b48", "3e00df82", "9e5c57bb", "ca6f8ca0", "1a87562e", "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573", "695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98", "fd2183b8", "4afcb56c", "2dd1d35b", "9a53e479", "b6f84565", "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341", "cee4c6e8", "ef20cada", "36774c01", "d07e9efe", "2bf11fb4", "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0", "d08ed1d0", "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64", "8888b812", "900df01c", "4fad5ea0", "688fc31c", "d1cff191", "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1", "e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0", "fd13e0b7", "7cc43b81", "d2ada8d9", "165fa266", "80957705", "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5", "fb9d35cf", "ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49", "00250e2d", "2071b35e", "226800bb", "57b8e0af", "2464369b", "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f", "207d5ba2", "02e5b9c5", "83260376", "6295cfa9", "11c81968", "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915", "d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5", "571be91f", "f296ec6b", "2a0dd915", "b6636521", "e7b9f9b6", "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799", "6e85076a", }, { "4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0", "49a7df7d", "9cee60b8", "8fedb266", "ecaa8c71", "699a17ff", "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340", "e4183a3e", "3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6", "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1", "4cdd2086", "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9", "3c971814", "6b6a70a1", "687f3584", "52a0e286", "b79c5305", "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8", "b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a", "3cb574b2", "25837a58", "dc0921bd", "d19113f9", "7ca92ff6", "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634", "9af3dda7", "a9446146", "0fd0030e", "ecc8c73e", "a4751e41", "e238cd99", "3bea0e2f", "3280bba1", "183eb331", "4e548b38", "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79", "5679b072", "bcaf89af", "de9a771f", "d9930810", "b38bae12", "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87", "7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a", "db851dfa", "63094366", "c464c3d2", "ef1c1847", "3215d908", "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002", "133ae4dd", "71dff89e", "10314e55", "81ac77d6", "5f11199b", "043556f1", "d7a3c76b", "3c11183b", "5924a509", "f28fe6ed", "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1", "860e5e0a", "5a3e2ab3", "771fe71c", "4e3d06fa", "2965dcb9", "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a", "c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7", "361d2b3d", "1939260f", "19c27960", "5223a708", "f71312b6", "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1", "018cff28", "c332ddef", "be6c5aa5", "65582185", "68ab9802", "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84", "1521b628", "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96", "0334fe1e", "aa0363cf", "b5735c90", "4c70a239", "d59e9e0b", "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e", "648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32", "3c2ab4b3", "319ee9d5", "c021b8f7", "9b540b19", "875fa099", "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f", "16681281", "0e358829", "c7e61fd6", "96dedfa1", "7858ba99", "57f584a5", "1b227263", "9b83c3ff", "1ac24696", "cdb30aeb", "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea", "fe28ed61", "ee7c3c73", "5d4a14d9", "e864b7e3", "42105d14", "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0", "c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e", "86854dc7", "e44b476a", "3d816250", "cf62a1f2", "5b8d2646", "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b", "5692b285", "095bbf00", "ad19489d", "1462b174", "23820e00", "58428d2a", "0c55f5ea", "1dadf43e", "233f7061", "3372f092", "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460", "4085f2a7", "ce77326e", "a6078084", "19f8509e", "e8efd855", "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc", "9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3", "105588cd", "675fda79", "e3674340", "c5c43465", "713e38d8", "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b", "db83adf7", }, { "e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7", "7602d4f7", "bcf46b2e", "d4a20068", "d4082471", "3320f46a", "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74", "bf8b8840", "4d95fc1d", "96b591af", "70f4ddd3", "66a02f45", "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504", "96eb27b3", "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4", "0a2c86da", "e9b66dfb", "68dc1462", "d7486900", "680ec0a4", "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6", "aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35", "d9f385b9", "ee39d7ab", "3b124e8b", "1dc9faf7", "4b6d1856", "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7", "ca7820fb", "fb0af54e", "d8feb397", "454056ac", "ba489527", "55533a3a", "20838d87", "fe6ba9b7", "d096954b", "55a867bc", "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9", "5ef47e1c", "9029317c", "fdf8e802", "04272f70", "80bb155c", "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc", "07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb", "d59bc0d1", "f2bcc18f", "41113564", "257b7834", "602a9c60", "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1", "cad18115", "6b2395e0", "333e92e1", "3b240b62", "eebeb922", "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728", "d0127845", "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa", "c39dfd27", "f33e8d1e", "0a476341", "992eff74", "3a6f6eab", "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d", "c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7", "cc00ffa3", "b5390f92", "690fed0b", "667b9ffb", "cedb7d9c", "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf", "763bd6eb", "37392eb3", "cc115979", "8026e297", "f42e312d", "6842ada7", "c66a2b3b", "12754ccc", "782ef11c", "6a124237", "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa", "3d25bdd8", "e2e1c3c9", "44421659", "0a121386", "d90cec6e", "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe", "9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346", "f6381fb0", "7745ae04", "d736fccc", "83426b33", "f01eab71", "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299", "bf582e61", "4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2", "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9", "7aeb2661", "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770", "8cd55591", "c902de4c", "b90bace1", "bb8205d0", "11a86248", "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633", "e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d", "0ba5a4df", "a186f20f", "2868f169", "dcb7da83", "573906fe", "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4", "0de6d027", "9af88c27", "773f8641", "c3604c06", "61a806b5", "f0177a28", "c0f586e0", "006058aa", "30dc7d62", "11e69ed7", "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de", "ebfc7da1", "ce591d76", "6f05e409", "4b7c0188", "39720a3d", "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc", "ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e", "b161e6f8", "a28514d9", "6c51133c", "6fd5c7e7", "56e14ec4", "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e", "406000e0", }, { "3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e", "4fa33742", "d3822740", "99bc9bbe", "d5118e9d", "bf0f7315", "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be", "6a366eb4", "5748ab2f", "bc946e79", "c6a376d2", "6549c2c8", "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6", "2939bbdb", "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a", "63ef8ce2", "9a86ee22", "c089c2b8", "43242ef6", "a51e03aa", "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6", "2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3", "f752f7da", "3f046f69", "77fa0a59", "80e4a915", "87b08601", "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9", "022b8b51", "96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28", "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c", "e029ac71", "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc", "f8d56629", "79132e28", "785f0191", "ed756055", "f7960e44", "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd", "c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b", "1e6321f5", "f59c66fb", "26dcf319", "7533d928", "b155fdf5", "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167", "ccad925f", "4de81751", "3830dc8e", "379d5862", "9320f991", "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32", "a8b6e37e", "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224", "69852dfd", "09072166", "b39a460a", "6445c0dd", "586cdecf", "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb", "dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8", "fa6484bb", "8d6612ae", "bf3c6f47", "d29be463", "542f5d9e", "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671", "af537d5d", "4040cb08", "4eb4e2cc", "34d2466a", "0115af84", "e1b00428", "95983a1d", "06b89fb4", "ce6ea048", "6f3f3b82", "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc", "bb3a792b", "344525bd", "a08839e1", "51ce794b", "2f32c9b7", "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7", "1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a", "c6913667", "8df9317c", "e0b12b4f", "f79e59b7", "43f5bb3a", "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71", "9b941525", "fae59361", "ceb69ceb", "c2a86459", "12baa8d1", "b6c1075e", "e3056a0c", "10d25065", "cb03a442", "e0ec6e0e", "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df", "d3a0342b", "8971f21e", "1b0a7441", "4ba3348c", "c5be7120", "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d", "e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166", "fd2c1d05", "848fd2c5", "f6fb2299", "f523f357", "a6327623", "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697", "88d273cc", "de966292", "81b949d0", "4c50901b", "71c65614", "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a", "c9aa53fd", "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222", "b6cbcf7c", "cd769c2b", "53113ec0", "1640e3d3", "38abbd60", "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060", "85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c", "02fb8a8c", "01c36ae4", "d6ebe1f9", "90d4f869", "a65cdea0", "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3", "3ac372e6", }, }; // Initializing subkeys with digits of pi String[] subKeys = { "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377", "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", "b5470917", "9216d5d9", "8979fb1b", }; // Initializing modVal to 2^32 long modVal = 4294967296L; /** * This method returns binary representation of the hexadecimal number passed as parameter * * @param hex Number for which binary representation is required * @return String object which is a binary representation of the hex number passed as parameter */ private String hexToBin(String hex) { StringBuilder binary = new StringBuilder(); long num; String binary4B; int n = hex.length(); for (int i = 0; i < n; i++) { num = Long.parseUnsignedLong(hex.charAt(i) + "", 16); binary4B = Long.toBinaryString(num); binary4B = "0000" + binary4B; binary4B = binary4B.substring(binary4B.length() - 4); binary.append(binary4B); } return binary.toString(); } /** * This method returns hexadecimal representation of the binary number passed as parameter * * @param binary Number for which hexadecimal representation is required * @return String object which is a hexadecimal representation of the binary number passed as * parameter */ private String binToHex(String binary) { long num = Long.parseUnsignedLong(binary, 2); StringBuilder hex = new StringBuilder(Long.toHexString(num)); while (hex.length() < (binary.length() / 4)) { hex.insert(0, "0"); } return hex.toString(); } /** * This method returns a string obtained by XOR-ing two strings of same length passed a method * parameters * * @param String a and b are string objects which will be XORed and are to be of same length * @return String object obtained by XOR operation on String a and String b * */ private String xor(String a, String b) { a = hexToBin(a); b = hexToBin(b); StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length(); i++) { ans.append((char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0')); } ans = new StringBuilder(binToHex(ans.toString())); return ans.toString(); } /** * This method returns addition of two hexadecimal numbers passed as parameters and moded with * 2^32 * * @param String a and b are hexadecimal numbers * @return String object which is a is addition that is then moded with 2^32 of hex numbers * passed as parameters */ private String addBin(String a, String b) { String ans = ""; long n1 = Long.parseUnsignedLong(a, 16); long n2 = Long.parseUnsignedLong(b, 16); n1 = (n1 + n2) % modVal; ans = Long.toHexString(n1); ans = "00000000" + ans; return ans.substring(ans.length() - 8); } /*F-function splits the 32-bit input into four 8-bit quarters and uses the quarters as input to the S-boxes. The S-boxes accept 8-bit input and produce 32-bit output. The outputs are added modulo 232 and XORed to produce the final 32-bit output */ private String f(String plainText) { String[] a = new String[4]; String ans = ""; for (int i = 0; i < 8; i += 2) { // column number for S-box is a 8-bit value long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2); a[i / 2] = sBox[i / 2][(int) col]; } ans = addBin(a[0], a[1]); ans = xor(ans, a[2]); ans = addBin(ans, a[3]); return ans; } // generate subkeys private void keyGenerate(String key) { int j = 0; for (int i = 0; i < subKeys.length; i++) { // XOR-ing 32-bit parts of the key with initial subkeys subKeys[i] = xor(subKeys[i], key.substring(j, j + 8)); j = (j + 8) % key.length(); } } // round function private String round(int time, String plainText) { String left; String right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, subKeys[time]); // output from F function String fOut = f(left); right = xor(fOut, right); // swap left and right return right + left; } /** * This method returns cipher text for the plaintext passed as the first parameter generated * using the key passed as the second parameter * * @param String plainText is the text which is to be encrypted * @param String key is the key which is to be used for generating cipher text * @return String cipherText is the encrypted value */ String encrypt(String plainText, String key) { // generating key keyGenerate(key); for (int i = 0; i < 16; i++) { plainText = round(i, plainText); } // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, subKeys[16]); left = xor(left, subKeys[17]); return left + right; } /** * This method returns plaintext for the ciphertext passed as the first parameter decoded * using the key passed as the second parameter * * @param String ciphertext is the text which is to be decrypted * @param String key is the key which is to be used for generating cipher text * @return String plainText is the decrypted text */ String decrypt(String cipherText, String key) { // generating key keyGenerate(key); for (int i = 17; i > 1; i--) { cipherText = round(i, cipherText); } // postprocessing String right = cipherText.substring(0, 8); String left = cipherText.substring(8, 16); right = xor(right, subKeys[1]); left = xor(left, subKeys[0]); return left + right; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/HillCipher.java
src/main/java/com/thealgorithms/ciphers/HillCipher.java
package com.thealgorithms.ciphers; public class HillCipher { // Encrypts the message using the key matrix public String encrypt(String message, int[][] keyMatrix) { message = message.toUpperCase().replaceAll("[^A-Z]", ""); int matrixSize = keyMatrix.length; validateDeterminant(keyMatrix, matrixSize); StringBuilder cipherText = new StringBuilder(); int[] messageVector = new int[matrixSize]; int[] cipherVector = new int[matrixSize]; int index = 0; while (index < message.length()) { for (int i = 0; i < matrixSize; i++) { if (index < message.length()) { messageVector[i] = message.charAt(index++) - 'A'; } else { messageVector[i] = 'X' - 'A'; // Padding with 'X' if needed } } for (int i = 0; i < matrixSize; i++) { cipherVector[i] = 0; for (int j = 0; j < matrixSize; j++) { cipherVector[i] += keyMatrix[i][j] * messageVector[j]; } cipherVector[i] = cipherVector[i] % 26; cipherText.append((char) (cipherVector[i] + 'A')); } } return cipherText.toString(); } // Decrypts the message using the inverse key matrix public String decrypt(String message, int[][] inverseKeyMatrix) { message = message.toUpperCase().replaceAll("[^A-Z]", ""); int matrixSize = inverseKeyMatrix.length; validateDeterminant(inverseKeyMatrix, matrixSize); StringBuilder plainText = new StringBuilder(); int[] messageVector = new int[matrixSize]; int[] plainVector = new int[matrixSize]; int index = 0; while (index < message.length()) { for (int i = 0; i < matrixSize; i++) { if (index < message.length()) { messageVector[i] = message.charAt(index++) - 'A'; } else { messageVector[i] = 'X' - 'A'; // Padding with 'X' if needed } } for (int i = 0; i < matrixSize; i++) { plainVector[i] = 0; for (int j = 0; j < matrixSize; j++) { plainVector[i] += inverseKeyMatrix[i][j] * messageVector[j]; } plainVector[i] = plainVector[i] % 26; plainText.append((char) (plainVector[i] + 'A')); } } return plainText.toString(); } // Validates that the determinant of the key matrix is not zero modulo 26 private void validateDeterminant(int[][] keyMatrix, int n) { int det = determinant(keyMatrix, n) % 26; if (det == 0) { throw new IllegalArgumentException("Invalid key matrix. Determinant is zero modulo 26."); } } // Computes the determinant of a matrix recursively private int determinant(int[][] matrix, int n) { int det = 0; if (n == 1) { return matrix[0][0]; } int sign = 1; int[][] subMatrix = new int[n - 1][n - 1]; for (int x = 0; x < n; x++) { int subI = 0; for (int i = 1; i < n; i++) { int subJ = 0; for (int j = 0; j < n; j++) { if (j != x) { subMatrix[subI][subJ++] = matrix[i][j]; } } subI++; } det += sign * matrix[0][x] * determinant(subMatrix, n - 1); sign = -sign; } return det; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/OneTimePadCipher.java
src/main/java/com/thealgorithms/ciphers/OneTimePadCipher.java
package com.thealgorithms.ciphers; import java.security.SecureRandom; import java.util.Objects; /** * One-Time Pad (OTP) cipher implementation. * * <p>The One-Time Pad is information-theoretically secure if: * <ul> * <li>The key is truly random.</li> * <li>The key length is at least as long as the plaintext.</li> * <li>The key is used only once and kept secret.</li> * </ul> * * <p>This implementation is for <b>educational purposes only</b> and should not be * used in production systems. */ public final class OneTimePadCipher { private static final SecureRandom RANDOM = new SecureRandom(); private OneTimePadCipher() { // utility class } /** * Generates a random key of the given length in bytes. * * @param length the length of the key in bytes, must be non-negative * @return a new random key * @throws IllegalArgumentException if length is negative */ public static byte[] generateKey(int length) { if (length < 0) { throw new IllegalArgumentException("length must be non-negative"); } byte[] key = new byte[length]; RANDOM.nextBytes(key); return key; } /** * Encrypts the given plaintext bytes using the provided key. * <p>The key length must be exactly the same as the plaintext length. * * @param plaintext the plaintext bytes, must not be {@code null} * @param key the one-time pad key bytes, must not be {@code null} * @return the ciphertext bytes * @throws IllegalArgumentException if the key length does not match plaintext length * @throws NullPointerException if plaintext or key is {@code null} */ public static byte[] encrypt(byte[] plaintext, byte[] key) { validateInputs(plaintext, key); return xor(plaintext, key); } /** * Decrypts the given ciphertext bytes using the provided key. * <p>For a One-Time Pad, decryption is identical to encryption: * {@code plaintext = ciphertext XOR key}. * * @param ciphertext the ciphertext bytes, must not be {@code null} * @param key the one-time pad key bytes, must not be {@code null} * @return the decrypted plaintext bytes * @throws IllegalArgumentException if the key length does not match ciphertext length * @throws NullPointerException if ciphertext or key is {@code null} */ public static byte[] decrypt(byte[] ciphertext, byte[] key) { validateInputs(ciphertext, key); return xor(ciphertext, key); } private static void validateInputs(byte[] input, byte[] key) { Objects.requireNonNull(input, "input must not be null"); Objects.requireNonNull(key, "key must not be null"); if (input.length != key.length) { throw new IllegalArgumentException("Key length must match input length"); } } private static byte[] xor(byte[] data, byte[] key) { byte[] result = new byte[data.length]; for (int i = 0; i < data.length; i++) { result[i] = (byte) (data[i] ^ key[i]); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
src/main/java/com/thealgorithms/ciphers/AffineCipher.java
package com.thealgorithms.ciphers; /** * The AffineCipher class implements the Affine cipher, a type of monoalphabetic substitution cipher. * It encrypts and decrypts messages using a linear transformation defined by the formula: * * E(x) = (a * x + b) mod m * D(y) = a^-1 * (y - b) mod m * * where: * - E(x) is the encrypted character, * - D(y) is the decrypted character, * - a is the multiplicative key (must be coprime to m), * - b is the additive key, * - x is the index of the plaintext character, * - y is the index of the ciphertext character, * - m is the size of the alphabet (26 for the English alphabet). * * The class provides methods for encrypting and decrypting messages, as well as a main method to demonstrate its usage. */ final class AffineCipher { private AffineCipher() { } // Key values of a and b static int a = 17; static int b = 20; /** * Encrypts a message using the Affine cipher. * * @param msg the plaintext message as a character array * @return the encrypted ciphertext */ static String encryptMessage(char[] msg) { // Cipher Text initially empty StringBuilder cipher = new StringBuilder(); for (int i = 0; i < msg.length; i++) { // Avoid space to be encrypted /* applying encryption formula ( a * x + b ) mod m {here x is msg[i] and m is 26} and added 'A' to bring it in the range of ASCII alphabet [65-90 | A-Z] */ if (msg[i] != ' ') { cipher.append((char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A')); } else { // else simply append space character cipher.append(msg[i]); } } return cipher.toString(); } /** * Decrypts a ciphertext using the Affine cipher. * * @param cipher the ciphertext to decrypt * @return the decrypted plaintext message */ static String decryptCipher(String cipher) { StringBuilder msg = new StringBuilder(); int aInv = 0; int flag; // Find a^-1 (the multiplicative inverse of a in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; // Check if (a * i) % 26 == 1, // then i will be the multiplicative inverse of a if (flag == 1) { aInv = i; break; } } for (int i = 0; i < cipher.length(); i++) { /* Applying decryption formula a^-1 * (x - b) mod m {here x is cipher[i] and m is 26} and added 'A' to bring it in the range of ASCII alphabet [65-90 | A-Z] */ if (cipher.charAt(i) != ' ') { msg.append((char) (((aInv * ((cipher.charAt(i) - 'A') - b + 26)) % 26) + 'A')); } else { // else simply append space character msg.append(cipher.charAt(i)); } } return msg.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/DiffieHellman.java
src/main/java/com/thealgorithms/ciphers/DiffieHellman.java
package com.thealgorithms.ciphers; import java.math.BigInteger; public final class DiffieHellman { private final BigInteger base; private final BigInteger secret; private final BigInteger prime; // Constructor to initialize base, secret, and prime public DiffieHellman(BigInteger base, BigInteger secret, BigInteger prime) { // Check for non-null and positive values if (base == null || secret == null || prime == null || base.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) { throw new IllegalArgumentException("Base, secret, and prime must be non-null and positive values."); } this.base = base; this.secret = secret; this.prime = prime; } // Method to calculate public value (g^x mod p) public BigInteger calculatePublicValue() { // Returns g^x mod p return base.modPow(secret, prime); } // Method to calculate the shared secret key (otherPublic^secret mod p) public BigInteger calculateSharedSecret(BigInteger otherPublicValue) { if (otherPublicValue == null || otherPublicValue.signum() <= 0) { throw new IllegalArgumentException("Other public value must be non-null and positive."); } // Returns b^x mod p or a^y mod p return otherPublicValue.modPow(secret, prime); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/RSA.java
src/main/java/com/thealgorithms/ciphers/RSA.java
package com.thealgorithms.ciphers; import java.math.BigInteger; import java.security.SecureRandom; /** * RSA is an asymmetric cryptographic algorithm used for secure data encryption and decryption. * It relies on a pair of keys: a public key (used for encryption) and a private key * (used for decryption). The algorithm is based on the difficulty of factoring large prime numbers. * * This implementation includes key generation, encryption, and decryption methods that can handle both * text-based messages and BigInteger inputs. For more details on RSA: * <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)">RSA Cryptosystem - Wikipedia</a>. * * Example Usage: * <pre> * RSA rsa = new RSA(1024); * String encryptedMessage = rsa.encrypt("Hello RSA!"); * String decryptedMessage = rsa.decrypt(encryptedMessage); * System.out.println(decryptedMessage); // Output: Hello RSA! * </pre> * * Note: The key size directly affects the security and performance of the RSA algorithm. * Larger keys are more secure but slower to compute. * * @author Nguyen Duy Tiep * @version 23-Oct-17 */ public class RSA { private BigInteger modulus; private BigInteger privateKey; private BigInteger publicKey; /** * Constructor that generates RSA keys with the specified number of bits. * * @param bits The bit length of the keys to be generated. Common sizes include 512, 1024, 2048, etc. */ public RSA(int bits) { generateKeys(bits); } /** * Encrypts a text message using the RSA public key. * * @param message The plaintext message to be encrypted. * @throws IllegalArgumentException If the message is empty. * @return The encrypted message represented as a String. */ public synchronized String encrypt(String message) { if (message.isEmpty()) { throw new IllegalArgumentException("Message is empty"); } return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); } /** * Encrypts a BigInteger message using the RSA public key. * * @param message The plaintext message as a BigInteger. * @return The encrypted message as a BigInteger. */ public synchronized BigInteger encrypt(BigInteger message) { return message.modPow(publicKey, modulus); } /** * Decrypts an encrypted message (as String) using the RSA private key. * * @param encryptedMessage The encrypted message to be decrypted, represented as a String. * @throws IllegalArgumentException If the message is empty. * @return The decrypted plaintext message as a String. */ public synchronized String decrypt(String encryptedMessage) { if (encryptedMessage.isEmpty()) { throw new IllegalArgumentException("Message is empty"); } return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); } /** * Decrypts an encrypted BigInteger message using the RSA private key. * * @param encryptedMessage The encrypted message as a BigInteger. * @return The decrypted plaintext message as a BigInteger. */ public synchronized BigInteger decrypt(BigInteger encryptedMessage) { return encryptedMessage.modPow(privateKey, modulus); } /** * Generates a new RSA key pair (public and private keys) with the specified bit length. * Steps: * 1. Generate two large prime numbers p and q. * 2. Compute the modulus n = p * q. * 3. Compute Euler's totient function: φ(n) = (p-1) * (q-1). * 4. Choose a public key e (starting from 3) that is coprime with φ(n). * 5. Compute the private key d as the modular inverse of e mod φ(n). * The public key is (e, n) and the private key is (d, n). * * @param bits The bit length of the keys to be generated. */ public final synchronized void generateKeys(int bits) { SecureRandom random = new SecureRandom(); BigInteger p = new BigInteger(bits / 2, 100, random); BigInteger q = new BigInteger(bits / 2, 100, random); modulus = p.multiply(q); BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); publicKey = BigInteger.valueOf(3L); while (phi.gcd(publicKey).intValue() > 1) { publicKey = publicKey.add(BigInteger.TWO); } privateKey = publicKey.modInverse(phi); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/Polybius.java
src/main/java/com/thealgorithms/ciphers/Polybius.java
package com.thealgorithms.ciphers; /** * A Java implementation of Polybius Cipher * Polybius is a substitution cipher method * It was invented by a greek philosopher that name is Polybius * Letters in alphabet takes place to two dimension table. * Encrypted text is created according to row and column in two dimension table * Decrypted text is generated by looking at the row and column respectively * Additionally, some letters in english alphabet deliberately throws such as U because U is very * similar with V * * @author Hikmet ÇAKIR * @since 08-07-2022+03:00 */ public final class Polybius { private Polybius() { } private static final char[][] KEY = { // 0 1 2 3 4 /* 0 */ {'A', 'B', 'C', 'D', 'E'}, /* 1 */ {'F', 'G', 'H', 'I', 'J'}, /* 2 */ {'K', 'L', 'M', 'N', 'O'}, /* 3 */ {'P', 'Q', 'R', 'S', 'T'}, /* 4 */ {'V', 'W', 'X', 'Y', 'Z'}, }; private static String findLocationByCharacter(final char character) { final StringBuilder location = new StringBuilder(); for (int i = 0; i < KEY.length; i++) { for (int j = 0; j < KEY[i].length; j++) { if (character == KEY[i][j]) { location.append(i).append(j); break; } } } return location.toString(); } public static String encrypt(final String plaintext) { final char[] chars = plaintext.toUpperCase().toCharArray(); final StringBuilder ciphertext = new StringBuilder(); for (char aChar : chars) { String location = findLocationByCharacter(aChar); ciphertext.append(location); } return ciphertext.toString(); } public static String decrypt(final String ciphertext) { final char[] chars = ciphertext.toCharArray(); final StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < chars.length; i += 2) { int pozitionX = Character.getNumericValue(chars[i]); int pozitionY = Character.getNumericValue(chars[i + 1]); plaintext.append(KEY[pozitionX][pozitionY]); } return plaintext.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
package com.thealgorithms.ciphers; import java.util.Objects; /** * Columnar Transposition Cipher Encryption and Decryption. * * @author <a href="https://github.com/freitzzz">freitzzz</a> */ public final class ColumnarTranspositionCipher { private ColumnarTranspositionCipher() { } private static String keyword; private static Object[][] table; private static String abecedarium; public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; private static final String ENCRYPTION_FIELD = "≈"; private static final char ENCRYPTION_FIELD_CHAR = '≈'; /** * Encrypts a certain String with the Columnar Transposition Cipher Rule * * @param word Word being encrypted * @param keyword String with keyword being used * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ public static String encrypt(final String word, final String keyword) { ColumnarTranspositionCipher.keyword = keyword; abecedariumBuilder(); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); StringBuilder wordEncrypted = new StringBuilder(); for (int i = 0; i < sortedTable[0].length; i++) { for (int j = 1; j < sortedTable.length; j++) { wordEncrypted.append(sortedTable[j][i]); } } return wordEncrypted.toString(); } /** * Encrypts a certain String with the Columnar Transposition Cipher Rule * * @param word Word being encrypted * @param keyword String with keyword being used * @param abecedarium String with the abecedarium being used. null for * default one * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ public static String encrypt(String word, String keyword, String abecedarium) { ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); StringBuilder wordEncrypted = new StringBuilder(); for (int i = 0; i < sortedTable[0].length; i++) { for (int j = 1; j < sortedTable.length; j++) { wordEncrypted.append(sortedTable[j][i]); } } return wordEncrypted.toString(); } /** * Decrypts a certain encrypted String with the Columnar Transposition * Cipher Rule * * @return a String decrypted with the word encrypted by the Columnar * Transposition Cipher Rule */ public static String decrypt() { StringBuilder wordDecrypted = new StringBuilder(); for (int i = 1; i < table.length; i++) { for (Object item : table[i]) { wordDecrypted.append(item); } } return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, ""); } /** * Builds a table with the word to be encrypted in rows by the Columnar * Transposition Cipher Rule * * @return An Object[][] with the word to be encrypted filled in rows and * columns */ private static Object[][] tableBuilder(String word) { Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()]; char[] wordInChars = word.toCharArray(); // Fills in the respective numbers for the column table[0] = findElements(); int charElement = 0; for (int i = 1; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { if (charElement < wordInChars.length) { table[i][j] = wordInChars[charElement]; charElement++; } else { table[i][j] = ENCRYPTION_FIELD_CHAR; } } } return table; } /** * Determines the number of rows the table should have regarding the * Columnar Transposition Cipher Rule * * @return an int with the number of rows that the table should have in * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { if (word.length() % keyword.length() != 0) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); } } /** * @return charValues */ private static Object[] findElements() { Object[] charValues = new Object[keyword.length()]; for (int i = 0; i < charValues.length; i++) { int charValueIndex = abecedarium.indexOf(keyword.charAt(i)); charValues[i] = charValueIndex > -1 ? charValueIndex : null; } return charValues; } /** * @return tableSorted */ private static Object[][] sortTable(Object[][] table) { Object[][] tableSorted = new Object[table.length][table[0].length]; for (int i = 0; i < tableSorted.length; i++) { System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); } for (int i = 0; i < tableSorted[0].length; i++) { for (int j = i + 1; j < tableSorted[0].length; j++) { if ((int) tableSorted[0][i] > (int) table[0][j]) { Object[] column = getColumn(tableSorted, tableSorted.length, i); switchColumns(tableSorted, j, i, column); } } } return tableSorted; } /** * @return columnArray */ private static Object[] getColumn(Object[][] table, int rows, int column) { Object[] columnArray = new Object[rows]; for (int i = 0; i < rows; i++) { columnArray[i] = table[i][column]; } return columnArray; } private static void switchColumns(Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { for (int i = 0; i < table.length; i++) { table[i][secondColumnIndex] = table[i][firstColumnIndex]; table[i][firstColumnIndex] = columnToSwitch[i]; } } /** * Creates an abecedarium with all available ascii values. */ private static void abecedariumBuilder() { StringBuilder t = new StringBuilder(); for (int i = 0; i < 256; i++) { t.append((char) i); } abecedarium = t.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
package com.thealgorithms.ciphers; import java.util.HashMap; import java.util.Map; /** * The simple substitution cipher is a cipher that has been in use for many * hundreds of years (an excellent history is given in Simon Singhs 'the Code * Book'). It basically consists of substituting every plaintext character for a * different ciphertext character. It differs from the Caesar cipher in that the * cipher alphabet is not simply the alphabet shifted, it is completely jumbled. */ public class SimpleSubCipher { /** * Encrypt text by replacing each element with its opposite character. * * @param message * @param cipherSmall * @return Encrypted message */ public String encode(String message, String cipherSmall) { StringBuilder encoded = new StringBuilder(); // This map is used to encode Map<Character, Character> cipherMap = new HashMap<>(); char beginSmallLetter = 'a'; char beginCapitalLetter = 'A'; cipherSmall = cipherSmall.toLowerCase(); String cipherCapital = cipherSmall.toUpperCase(); // To handle Small and Capital letters for (int i = 0; i < cipherSmall.length(); i++) { cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i)); cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i)); } for (int i = 0; i < message.length(); i++) { if (Character.isAlphabetic(message.charAt(i))) { encoded.append(cipherMap.get(message.charAt(i))); } else { encoded.append(message.charAt(i)); } } return encoded.toString(); } /** * Decrypt message by replacing each element with its opposite character in * cipher. * * @param encryptedMessage * @param cipherSmall * @return message */ public String decode(String encryptedMessage, String cipherSmall) { StringBuilder decoded = new StringBuilder(); Map<Character, Character> cipherMap = new HashMap<>(); char beginSmallLetter = 'a'; char beginCapitalLetter = 'A'; cipherSmall = cipherSmall.toLowerCase(); String cipherCapital = cipherSmall.toUpperCase(); for (int i = 0; i < cipherSmall.length(); i++) { cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++); cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++); } for (int i = 0; i < encryptedMessage.length(); i++) { if (Character.isAlphabetic(encryptedMessage.charAt(i))) { decoded.append(cipherMap.get(encryptedMessage.charAt(i))); } else { decoded.append(encryptedMessage.charAt(i)); } } return decoded.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/MonoAlphabetic.java
src/main/java/com/thealgorithms/ciphers/MonoAlphabetic.java
package com.thealgorithms.ciphers; public final class MonoAlphabetic { private MonoAlphabetic() { throw new UnsupportedOperationException("Utility class"); } // Encryption method public static String encrypt(String data, String key) { if (!data.matches("[A-Z]+")) { throw new IllegalArgumentException("Input data contains invalid characters. Only uppercase A-Z are allowed."); } StringBuilder sb = new StringBuilder(); // Encrypt each character for (char c : data.toCharArray()) { int idx = charToPos(c); // Get the index of the character sb.append(key.charAt(idx)); // Map to the corresponding character in the key } return sb.toString(); } // Decryption method public static String decrypt(String data, String key) { StringBuilder sb = new StringBuilder(); // Decrypt each character for (char c : data.toCharArray()) { int idx = key.indexOf(c); // Find the index of the character in the key if (idx == -1) { throw new IllegalArgumentException("Input data contains invalid characters."); } sb.append(posToChar(idx)); // Convert the index back to the original character } return sb.toString(); } // Helper method: Convert a character to its position in the alphabet private static int charToPos(char c) { return c - 'A'; // Subtract 'A' to get position (0 for A, 1 for B, etc.) } // Helper method: Convert a position in the alphabet to a character private static char posToChar(int pos) { return (char) (pos + 'A'); // Add 'A' to convert position back to character } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java
src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java
package com.thealgorithms.ciphers; public class PlayfairCipher { private char[][] matrix; private String key; public PlayfairCipher(String key) { this.key = key; generateMatrix(); } public String encrypt(String plaintext) { plaintext = prepareText(plaintext.replace("J", "I")); StringBuilder ciphertext = new StringBuilder(); for (int i = 0; i < plaintext.length(); i += 2) { char char1 = plaintext.charAt(i); char char2 = plaintext.charAt(i + 1); int[] pos1 = findPosition(char1); int[] pos2 = findPosition(char2); int row1 = pos1[0]; int col1 = pos1[1]; int row2 = pos2[0]; int col2 = pos2[1]; if (row1 == row2) { ciphertext.append(matrix[row1][(col1 + 1) % 5]); ciphertext.append(matrix[row2][(col2 + 1) % 5]); } else if (col1 == col2) { ciphertext.append(matrix[(row1 + 1) % 5][col1]); ciphertext.append(matrix[(row2 + 1) % 5][col2]); } else { ciphertext.append(matrix[row1][col2]); ciphertext.append(matrix[row2][col1]); } } return ciphertext.toString(); } public String decrypt(String ciphertext) { StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < ciphertext.length(); i += 2) { char char1 = ciphertext.charAt(i); char char2 = ciphertext.charAt(i + 1); int[] pos1 = findPosition(char1); int[] pos2 = findPosition(char2); int row1 = pos1[0]; int col1 = pos1[1]; int row2 = pos2[0]; int col2 = pos2[1]; if (row1 == row2) { plaintext.append(matrix[row1][(col1 + 4) % 5]); plaintext.append(matrix[row2][(col2 + 4) % 5]); } else if (col1 == col2) { plaintext.append(matrix[(row1 + 4) % 5][col1]); plaintext.append(matrix[(row2 + 4) % 5][col2]); } else { plaintext.append(matrix[row1][col2]); plaintext.append(matrix[row2][col1]); } } return plaintext.toString(); } private void generateMatrix() { String keyWithoutDuplicates = removeDuplicateChars(key + "ABCDEFGHIKLMNOPQRSTUVWXYZ"); matrix = new char[5][5]; int index = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { matrix[i][j] = keyWithoutDuplicates.charAt(index); index++; } } } private String removeDuplicateChars(String str) { StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { if (result.indexOf(String.valueOf(str.charAt(i))) == -1) { result.append(str.charAt(i)); } } return result.toString(); } private String prepareText(String text) { text = text.toUpperCase().replaceAll("[^A-Z]", ""); StringBuilder preparedText = new StringBuilder(); char prevChar = '\0'; for (char c : text.toCharArray()) { if (c != prevChar) { preparedText.append(c); prevChar = c; } else { preparedText.append('X').append(c); prevChar = '\0'; } } if (preparedText.length() % 2 != 0) { preparedText.append('X'); } return preparedText.toString(); } private int[] findPosition(char c) { int[] pos = new int[2]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (matrix[i][j] == c) { pos[0] = i; pos[1] = j; return pos; } } } return pos; } public void printMatrix() { System.out.println("\nPlayfair Cipher Matrix:"); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/XORCipher.java
src/main/java/com/thealgorithms/ciphers/XORCipher.java
package com.thealgorithms.ciphers; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.HexFormat; /** * A simple implementation of the XOR cipher that allows both encryption and decryption * using a given key. This cipher works by applying the XOR bitwise operation between * the bytes of the input text and the corresponding bytes of the key (repeating the key * if necessary). * * Usage: * - Encryption: Converts plaintext into a hexadecimal-encoded ciphertext. * - Decryption: Converts the hexadecimal ciphertext back into plaintext. * * Characteristics: * - Symmetric: The same key is used for both encryption and decryption. * - Simple but vulnerable: XOR encryption is insecure for real-world cryptography, * especially when the same key is reused. * * Example: * Plaintext: "Hello!" * Key: "key" * Encrypted: "27090c03120b" * Decrypted: "Hello!" * * Reference: <a href="https://en.wikipedia.org/wiki/XOR_cipher">XOR Cipher - Wikipedia</a> * * @author <a href="https://github.com/lcsjunior">lcsjunior</a> */ public final class XORCipher { // Default character encoding for string conversion private static final Charset CS_DEFAULT = StandardCharsets.UTF_8; private XORCipher() { } /** * Applies the XOR operation between the input bytes and the key bytes. * If the key is shorter than the input, it wraps around (cyclically). * * @param inputBytes The input byte array (plaintext or ciphertext). * @param keyBytes The key byte array used for XOR operation. * @return A new byte array containing the XOR result. */ public static byte[] xor(final byte[] inputBytes, final byte[] keyBytes) { byte[] outputBytes = new byte[inputBytes.length]; for (int i = 0; i < inputBytes.length; ++i) { outputBytes[i] = (byte) (inputBytes[i] ^ keyBytes[i % keyBytes.length]); } return outputBytes; } /** * Encrypts the given plaintext using the XOR cipher with the specified key. * The result is a hexadecimal-encoded string representing the ciphertext. * * @param plainText The input plaintext to encrypt. * @param key The encryption key. * @throws IllegalArgumentException if the key is empty. * @return A hexadecimal string representing the encrypted text. */ public static String encrypt(final String plainText, final String key) { if (key.isEmpty()) { throw new IllegalArgumentException("Key must not be empty"); } byte[] plainTextBytes = plainText.getBytes(CS_DEFAULT); byte[] keyBytes = key.getBytes(CS_DEFAULT); byte[] xorResult = xor(plainTextBytes, keyBytes); return HexFormat.of().formatHex(xorResult); } /** * Decrypts the given ciphertext (in hexadecimal format) using the XOR cipher * with the specified key. The result is the original plaintext. * * @param cipherText The hexadecimal string representing the encrypted text. * @param key The decryption key (must be the same as the encryption key). * @throws IllegalArgumentException if the key is empty. * @return The decrypted plaintext. */ public static String decrypt(final String cipherText, final String key) { if (key.isEmpty()) { throw new IllegalArgumentException("Key must not be empty"); } byte[] cipherBytes = HexFormat.of().parseHex(cipherText); byte[] keyBytes = key.getBytes(CS_DEFAULT); byte[] xorResult = xor(cipherBytes, keyBytes); return new String(xorResult, CS_DEFAULT); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/Caesar.java
src/main/java/com/thealgorithms/ciphers/Caesar.java
package com.thealgorithms.ciphers; /** * A Java implementation of Caesar Cipher. /It is a type of substitution cipher * in which each letter in the plaintext is replaced by a letter some fixed * number of positions down the alphabet. / * * @author FAHRI YARDIMCI * @author khalil2535 */ public class Caesar { private static char normalizeShift(final int shift) { return (char) (shift % 26); } /** * Encrypt text by shifting every Latin char by add number shift for ASCII * Example : A + 1 -> B * * @return Encrypted message */ public String encode(String message, int shift) { StringBuilder encoded = new StringBuilder(); final char shiftChar = normalizeShift(shift); final int length = message.length(); for (int i = 0; i < length; i++) { // int current = message.charAt(i); //using char to shift characters because // ascii // is in-order latin alphabet char current = message.charAt(i); // Java law : char + int = char if (isCapitalLatinLetter(current)) { current += shiftChar; encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters } else if (isSmallLatinLetter(current)) { current += shiftChar; encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters } else { encoded.append(current); } } return encoded.toString(); } /** * Decrypt message by shifting back every Latin char to previous the ASCII * Example : B - 1 -> A * * @return message */ public String decode(String encryptedMessage, int shift) { StringBuilder decoded = new StringBuilder(); final char shiftChar = normalizeShift(shift); final int length = encryptedMessage.length(); for (int i = 0; i < length; i++) { char current = encryptedMessage.charAt(i); if (isCapitalLatinLetter(current)) { current -= shiftChar; decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters } else if (isSmallLatinLetter(current)) { current -= shiftChar; decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters } else { decoded.append(current); } } return decoded.toString(); } /** * @return true if character is capital Latin letter or false for others */ private static boolean isCapitalLatinLetter(char c) { return c >= 'A' && c <= 'Z'; } /** * @return true if character is small Latin letter or false for others */ private static boolean isSmallLatinLetter(char c) { return c >= 'a' && c <= 'z'; } /** * @return string array which contains all the possible decoded combination. */ public String[] bruteforce(String encryptedMessage) { String[] listOfAllTheAnswers = new String[27]; for (int i = 0; i <= 26; i++) { listOfAllTheAnswers[i] = decode(encryptedMessage, i); } return listOfAllTheAnswers; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/DES.java
src/main/java/com/thealgorithms/ciphers/DES.java
package com.thealgorithms.ciphers; /** * This class is build to demonstrate the application of the DES-algorithm * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied * key must be in form of a 64 bit binary String. */ public class DES { private String key; private final String[] subKeys; private void sanitize(String key) { int length = key.length(); if (length != 64) { throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string"); } } DES(String key) { sanitize(key); this.key = key; subKeys = getSubkeys(key); } public String getKey() { return this.key; } public void setKey(String key) { sanitize(key); this.key = key; } // Permutation table to convert initial 64-bit key to 56 bit key private static final int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4}; // Lookup table used to shift the initial key, in order to generate the subkeys private static final int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; // Table to convert the 56 bit subkeys to 48 bit subkeys private static final int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32}; // Initial permutation of each 64 but message block private static final int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7}; // Expansion table to convert right half of message blocks from 32 bits to 48 bits private static final int[] EXPANSION = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1}; // The eight substitution boxes are defined below private static final int[][] S1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}}; private static final int[][] S2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}}; private static final int[][] S3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}}; private static final int[][] S4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}}; private static final int[][] S5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}}; private static final int[][] S6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}}; private static final int[][] S7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}}; private static final int[][] S8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}}; private static final int[][][] S = {S1, S2, S3, S4, S5, S6, S7, S8}; // Permutation table, used in the Feistel function post s-box usage static final int[] PERMUTATION = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; // Table used for final inversion of the message box after 16 rounds of Feistel Function static final int[] IP_INVERSE = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25}; private String[] getSubkeys(String originalKey) { StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via pc1 int i; int j; for (i = 0; i < 56; i++) { permutedKey.append(originalKey.charAt(PC1[i] - 1)); } String[] subKeys = new String[16]; String initialPermutedKey = permutedKey.toString(); String c0 = initialPermutedKey.substring(0, 28); String d0 = initialPermutedKey.substring(28); // We will now operate on the left and right halves of the permutedKey for (i = 0; i < 16; i++) { String cN = c0.substring(KEY_SHIFTS[i]) + c0.substring(0, KEY_SHIFTS[i]); String dN = d0.substring(KEY_SHIFTS[i]) + d0.substring(0, KEY_SHIFTS[i]); subKeys[i] = cN + dN; c0 = cN; // Re-assign the values to create running permutation d0 = dN; } // Let us shrink the keys to 48 bits (well, characters here) using pc2 for (i = 0; i < 16; i++) { String key = subKeys[i]; permutedKey.setLength(0); for (j = 0; j < 48; j++) { permutedKey.append(key.charAt(PC2[j] - 1)); } subKeys[i] = permutedKey.toString(); } return subKeys; } private String xOR(String a, String b) { int i; int l = a.length(); StringBuilder xor = new StringBuilder(); for (i = 0; i < l; i++) { int firstBit = a.charAt(i) - 48; // 48 is '0' in ascii int secondBit = b.charAt(i) - 48; xor.append((firstBit ^ secondBit)); } return xor.toString(); } private String createPaddedString(String s, int desiredLength, char pad) { int i; int l = s.length(); StringBuilder paddedString = new StringBuilder(); int diff = desiredLength - l; for (i = 0; i < diff; i++) { paddedString.append(pad); } return paddedString.toString(); } private String pad(String s, int desiredLength) { return createPaddedString(s, desiredLength, '0') + s; } private String padLast(String s, int desiredLength) { return s + createPaddedString(s, desiredLength, '\u0000'); } private String feistel(String messageBlock, String key) { int i; StringBuilder expandedKey = new StringBuilder(); for (i = 0; i < 48; i++) { expandedKey.append(messageBlock.charAt(EXPANSION[i] - 1)); } String mixedKey = xOR(expandedKey.toString(), key); StringBuilder substitutedString = new StringBuilder(); // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits for (i = 0; i < 48; i += 6) { String block = mixedKey.substring(i, i + 6); int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48); int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48); String substitutedBlock = pad(Integer.toBinaryString(S[i / 6][row][col]), 4); substitutedString.append(substitutedBlock); } StringBuilder permutedString = new StringBuilder(); for (i = 0; i < 32; i++) { permutedString.append(substitutedString.charAt(PERMUTATION[i] - 1)); } return permutedString.toString(); } private String encryptBlock(String message, String[] keys) { StringBuilder permutedMessage = new StringBuilder(); int i; for (i = 0; i < 64; i++) { permutedMessage.append(message.charAt(IP[i] - 1)); } String e0 = permutedMessage.substring(0, 32); String f0 = permutedMessage.substring(32); // Iterate 16 times for (i = 0; i < 16; i++) { String eN = f0; // Previous Right block String fN = xOR(e0, feistel(f0, keys[i])); e0 = eN; f0 = fN; } String combinedBlock = f0 + e0; // Reverse the 16th block permutedMessage.setLength(0); for (i = 0; i < 64; i++) { permutedMessage.append(combinedBlock.charAt(IP_INVERSE[i] - 1)); } return permutedMessage.toString(); } // To decode, we follow the same process as encoding, but with reversed keys private String decryptBlock(String message, String[] keys) { String[] reversedKeys = new String[keys.length]; for (int i = 0; i < keys.length; i++) { reversedKeys[i] = keys[keys.length - i - 1]; } return encryptBlock(message, reversedKeys); } /** * @param message Message to be encrypted * @return The encrypted message, as a binary string */ public String encrypt(String message) { StringBuilder encryptedMessage = new StringBuilder(); int l = message.length(); int i; int j; if (l % 8 != 0) { int desiredLength = (l / 8 + 1) * 8; l = desiredLength; message = padLast(message, desiredLength); } for (i = 0; i < l; i += 8) { String block = message.substring(i, i + 8); StringBuilder bitBlock = new StringBuilder(); byte[] bytes = block.getBytes(); for (j = 0; j < 8; j++) { bitBlock.append(pad(Integer.toBinaryString(bytes[j]), 8)); } encryptedMessage.append(encryptBlock(bitBlock.toString(), subKeys)); } return encryptedMessage.toString(); } /** * @param message The encrypted string. Expects it to be a multiple of 64 bits, in binary format * @return The decrypted String, in plain English */ public String decrypt(String message) { StringBuilder decryptedMessage = new StringBuilder(); int l = message.length(); int i; int j; if (l % 64 != 0) { throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length"); } for (i = 0; i < l; i += 64) { String block = message.substring(i, i + 64); String result = decryptBlock(block, subKeys); byte[] res = new byte[8]; for (j = 0; j < 64; j += 8) { res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2); } decryptedMessage.append(new String(res)); } return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/ECC.java
src/main/java/com/thealgorithms/ciphers/ECC.java
package com.thealgorithms.ciphers; import java.math.BigInteger; import java.security.SecureRandom; /** * ECC - Elliptic Curve Cryptography * Elliptic Curve Cryptography is a public-key cryptography method that uses the algebraic structure of * elliptic curves over finite fields. ECC provides a higher level of security with smaller key sizes compared * to other public-key methods like RSA, making it particularly suitable for environments where computational * resources are limited, such as mobile devices and embedded systems. * * This class implements elliptic curve cryptography, providing encryption and decryption * functionalities based on public and private key pairs. * * @author xuyang */ public class ECC { private BigInteger privateKey; // Private key used for decryption private ECPoint publicKey; // Public key used for encryption private EllipticCurve curve; // Elliptic curve used in cryptography private ECPoint basePoint; // Base point G on the elliptic curve public ECC(int bits) { generateKeys(bits); // Generates public-private key pair } public EllipticCurve getCurve() { return curve; // Returns the elliptic curve } public void setCurve(EllipticCurve curve) { this.curve = curve; } // Getter and Setter for private key public BigInteger getPrivateKey() { return privateKey; } public void setPrivateKey(BigInteger privateKey) { this.privateKey = privateKey; } /** * Encrypts the message using the public key. * The message is transformed into an ECPoint and encrypted with elliptic curve operations. * * @param message The plain message to be encrypted * @return The encrypted message as an array of ECPoints (R, S) */ public ECPoint[] encrypt(String message) { BigInteger m = new BigInteger(message.getBytes()); // Convert message to BigInteger SecureRandom r = new SecureRandom(); // Generate random value for k BigInteger k = new BigInteger(curve.getFieldSize(), r); // Generate random scalar k // Calculate point r = k * G, where G is the base point ECPoint rPoint = basePoint.multiply(k, curve.getP(), curve.getA()); // Calculate point s = k * publicKey + encodedMessage ECPoint sPoint = publicKey.multiply(k, curve.getP(), curve.getA()).add(curve.encodeMessage(m), curve.getP(), curve.getA()); return new ECPoint[] {rPoint, sPoint}; // Return encrypted message as two ECPoints } /** * Decrypts the encrypted message using the private key. * The decryption process is the reverse of encryption, recovering the original message. * * @param encryptedMessage The encrypted message as an array of ECPoints (R, S) * @return The decrypted plain message as a String */ public String decrypt(ECPoint[] encryptedMessage) { ECPoint rPoint = encryptedMessage[0]; // First part of ciphertext ECPoint sPoint = encryptedMessage[1]; // Second part of ciphertext // Perform decryption: s - r * privateKey ECPoint decodedMessage = sPoint.subtract(rPoint.multiply(privateKey, curve.getP(), curve.getA()), curve.getP(), curve.getA()); BigInteger m = curve.decodeMessage(decodedMessage); // Decode the message from ECPoint return new String(m.toByteArray()); // Convert BigInteger back to String } /** * Generates a new public-private key pair for encryption and decryption. * * @param bits The size (in bits) of the keys to generate */ public final void generateKeys(int bits) { SecureRandom r = new SecureRandom(); curve = new EllipticCurve(bits); // Initialize a new elliptic curve basePoint = curve.getBasePoint(); // Set the base point G // Generate private key as a random BigInteger privateKey = new BigInteger(bits, r); // Generate public key as the point publicKey = privateKey * G publicKey = basePoint.multiply(privateKey, curve.getP(), curve.getA()); } /** * Class representing an elliptic curve with the form y^2 = x^3 + ax + b. */ public static class EllipticCurve { private final BigInteger a; // Coefficient a in the curve equation private final BigInteger b; // Coefficient b in the curve equation private final BigInteger p; // Prime number p, defining the finite field private final ECPoint basePoint; // Base point G on the curve // Constructor with explicit parameters for a, b, p, and base point public EllipticCurve(BigInteger a, BigInteger b, BigInteger p, ECPoint basePoint) { this.a = a; this.b = b; this.p = p; this.basePoint = basePoint; } // Constructor that randomly generates the curve parameters public EllipticCurve(int bits) { SecureRandom r = new SecureRandom(); this.p = BigInteger.probablePrime(bits, r); // Random prime p this.a = new BigInteger(bits, r); // Random coefficient a this.b = new BigInteger(bits, r); // Random coefficient b this.basePoint = new ECPoint(BigInteger.valueOf(4), BigInteger.valueOf(8)); // Fixed base point G } public ECPoint getBasePoint() { return basePoint; } public BigInteger getP() { return p; } public BigInteger getA() { return a; } public BigInteger getB() { return b; } public int getFieldSize() { return p.bitLength(); } public ECPoint encodeMessage(BigInteger message) { // Simple encoding of a message as an ECPoint (this is a simplified example) return new ECPoint(message, message); } public BigInteger decodeMessage(ECPoint point) { return point.getX(); // Decode the message from ECPoint (simplified) } } /** * Class representing a point on the elliptic curve. */ public static class ECPoint { private final BigInteger x; // X-coordinate of the point private final BigInteger y; // Y-coordinate of the point public ECPoint(BigInteger x, BigInteger y) { this.x = x; this.y = y; } public BigInteger getX() { return x; } public BigInteger getY() { return y; } @Override public String toString() { return "ECPoint(x=" + x.toString() + ", y=" + y.toString() + ")"; } /** * Add two points on the elliptic curve. */ public ECPoint add(ECPoint other, BigInteger p, BigInteger a) { if (this.x.equals(BigInteger.ZERO) && this.y.equals(BigInteger.ZERO)) { return other; // If this point is the identity, return the other point } if (other.x.equals(BigInteger.ZERO) && other.y.equals(BigInteger.ZERO)) { return this; // If the other point is the identity, return this point } BigInteger lambda; if (this.equals(other)) { // Special case: point doubling lambda = this.x.pow(2).multiply(BigInteger.valueOf(3)).add(a).multiply(this.y.multiply(BigInteger.valueOf(2)).modInverse(p)).mod(p); } else { // General case: adding two different points lambda = other.y.subtract(this.y).multiply(other.x.subtract(this.x).modInverse(p)).mod(p); } BigInteger xr = lambda.pow(2).subtract(this.x).subtract(other.x).mod(p); BigInteger yr = lambda.multiply(this.x.subtract(xr)).subtract(this.y).mod(p); return new ECPoint(xr, yr); } /** * Subtract two points on the elliptic curve. */ public ECPoint subtract(ECPoint other, BigInteger p, BigInteger a) { ECPoint negOther = new ECPoint(other.x, p.subtract(other.y)); // Negate the Y coordinate return this.add(negOther, p, a); // Add the negated point } /** * Multiply a point by a scalar (repeated addition). */ public ECPoint multiply(BigInteger k, BigInteger p, BigInteger a) { ECPoint result = new ECPoint(BigInteger.ZERO, BigInteger.ZERO); // Identity point ECPoint addend = this; while (k.signum() > 0) { if (k.testBit(0)) { result = result.add(addend, p, a); // Add the current point } addend = addend.add(addend, p, a); // Double the point k = k.shiftRight(1); // Divide k by 2 } return result; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java
src/main/java/com/thealgorithms/ciphers/BaconianCipher.java
package com.thealgorithms.ciphers; import java.util.HashMap; import java.util.Map; /** * The Baconian Cipher is a substitution cipher where each letter is represented * by a group of five binary digits (A's and B's). It can also be used to hide * messages within other texts, making it a simple form of steganography. * https://en.wikipedia.org/wiki/Bacon%27s_cipher * * @author Bennybebo */ public class BaconianCipher { private static final Map<Character, String> BACONIAN_MAP = new HashMap<>(); private static final Map<String, Character> REVERSE_BACONIAN_MAP = new HashMap<>(); static { // Initialize the Baconian cipher mappings String[] baconianAlphabet = {"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB", "BABAA", "BABAB", "BABBA", "BABBB", "BBAAA", "BBAAB"}; char letter = 'A'; for (String code : baconianAlphabet) { BACONIAN_MAP.put(letter, code); REVERSE_BACONIAN_MAP.put(code, letter); letter++; } // Handle I/J as the same letter BACONIAN_MAP.put('I', BACONIAN_MAP.get('J')); REVERSE_BACONIAN_MAP.put(BACONIAN_MAP.get('I'), 'I'); } /** * Encrypts the given plaintext using the Baconian cipher. * * @param plaintext The plaintext message to encrypt. * @return The ciphertext as a binary (A/B) sequence. */ public String encrypt(String plaintext) { StringBuilder ciphertext = new StringBuilder(); plaintext = plaintext.toUpperCase().replaceAll("[^A-Z]", ""); // Remove non-letter characters for (char letter : plaintext.toCharArray()) { ciphertext.append(BACONIAN_MAP.get(letter)); } return ciphertext.toString(); } /** * Decrypts the given ciphertext encoded in binary (A/B) format using the Baconian cipher. * * @param ciphertext The ciphertext to decrypt. * @return The decrypted plaintext message. */ public String decrypt(String ciphertext) { StringBuilder plaintext = new StringBuilder(); for (int i = 0; i < ciphertext.length(); i += 5) { String code = ciphertext.substring(i, i + 5); if (REVERSE_BACONIAN_MAP.containsKey(code)) { plaintext.append(REVERSE_BACONIAN_MAP.get(code)); } else { throw new IllegalArgumentException("Invalid Baconian code: " + code); } } return plaintext.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
src/main/java/com/thealgorithms/ciphers/AESEncryption.java
package com.thealgorithms.ciphers; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; /** * This example program shows how AES encryption and decryption can be done in * Java. Please note that secret key and encrypted text is unreadable binary and * hence in the following program we display it in hexadecimal format of the * underlying bytes. */ public final class AESEncryption { private AESEncryption() { } private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); private static Cipher aesCipher; /** * 1. Generate a plain text for encryption 2. Get a secret key (printed in * hexadecimal form). In actual use this must be encrypted and kept safe. * The same key is required for decryption. */ public static void main(String[] args) throws Exception { String plainText = "Hello World"; SecretKey secKey = getSecretEncryptionKey(); byte[] cipherText = encryptText(plainText, secKey); String decryptedText = decryptText(cipherText, secKey); System.out.println("Original Text:" + plainText); System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); System.out.println("Descrypted Text:" + decryptedText); } /** * gets the AES encryption key. In your actual programs, this should be * safely stored. * * @return secKey (Secret key that we encrypt using it) * @throws NoSuchAlgorithmException (from KeyGenrator) */ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); aesKeyGenerator.init(128); // The AES key size in number of bits return aesKeyGenerator.generateKey(); } /** * Encrypts plainText in AES using the secret key * * @return byteCipherText (The encrypted text) * @throws NoSuchPaddingException (from Cipher) * @throws NoSuchAlgorithmException (from Cipher) * @throws InvalidKeyException (from Cipher) * @throws BadPaddingException (from Cipher) * @throws IllegalBlockSizeException (from Cipher) */ public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); return aesCipher.doFinal(plainText.getBytes()); } /** * Decrypts encrypted byte array using the key used for encryption. * * @return plainText */ public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV()); decryptionCipher.init(Cipher.DECRYPT_MODE, secKey, gcmParameterSpec); byte[] bytePlainText = decryptionCipher.doFinal(byteCipherText); return new String(bytePlainText); } /** * Convert a binary byte array into readable hex form Old library is * deprecated on OpenJdk 11 and this is faster regarding other solution is * using StringBuilder * * @return hexHash */ public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/LFSR.java
src/main/java/com/thealgorithms/ciphers/a5/LFSR.java
package com.thealgorithms.ciphers.a5; import java.util.BitSet; public class LFSR implements BaseLFSR { private final BitSet register; private final int length; private final int clockBitIndex; private final int[] tappingBitsIndices; public LFSR(int length, int clockBitIndex, int[] tappingBitsIndices) { this.length = length; this.clockBitIndex = clockBitIndex; this.tappingBitsIndices = tappingBitsIndices; register = new BitSet(length); } @Override public void initialize(BitSet sessionKey, BitSet frameCounter) { register.clear(); clock(sessionKey, SESSION_KEY_LENGTH); clock(frameCounter, FRAME_COUNTER_LENGTH); } private void clock(BitSet key, int keyLength) { // We start from reverse because LFSR 0 index is the left most bit // while key 0 index is right most bit, so we reverse it for (int i = keyLength - 1; i >= 0; --i) { var newBit = key.get(i) ^ xorTappingBits(); pushBit(newBit); } } @Override public boolean clock() { return pushBit(xorTappingBits()); } public boolean getClockBit() { return register.get(clockBitIndex); } public boolean get(int bitIndex) { return register.get(bitIndex); } public boolean getLastBit() { return register.get(length - 1); } private boolean xorTappingBits() { boolean result = false; for (int i : tappingBitsIndices) { result ^= register.get(i); } return result; } private boolean pushBit(boolean bit) { boolean discardedBit = rightShift(); register.set(0, bit); return discardedBit; } private boolean rightShift() { boolean discardedBit = get(length - 1); for (int i = length - 1; i > 0; --i) { register.set(i, get(i - 1)); } register.set(0, false); return discardedBit; } @Override public String toString() { return register.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java
src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java
package com.thealgorithms.ciphers.a5; import java.util.BitSet; public interface BaseLFSR { void initialize(BitSet sessionKey, BitSet frameCounter); boolean clock(); int SESSION_KEY_LENGTH = 64; int FRAME_COUNTER_LENGTH = 22; }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
package com.thealgorithms.ciphers.a5; import java.util.BitSet; /** * The A5KeyStreamGenerator class is responsible for generating key streams * for the A5/1 encryption algorithm using a combination of Linear Feedback Shift Registers (LFSRs). * * <p> * This class extends the CompositeLFSR and initializes a set of LFSRs with * a session key and a frame counter to produce a pseudo-random key stream. * </p> * * <p> * Note: Proper exception handling for invalid usage is to be implemented. * </p> */ public class A5KeyStreamGenerator extends CompositeLFSR { private BitSet initialFrameCounter; private BitSet frameCounter; private BitSet sessionKey; private static final int INITIAL_CLOCKING_CYCLES = 100; private static final int KEY_STREAM_LENGTH = 228; /** * Initializes the A5KeyStreamGenerator with the specified session key and frame counter. * * <p> * This method sets up the internal state of the LFSRs using the provided * session key and frame counter. It creates three LFSRs with specific * configurations and initializes them. * </p> * * @param sessionKey a BitSet representing the session key used for key stream generation. * @param frameCounter a BitSet representing the frame counter that influences the key stream. */ @Override public void initialize(BitSet sessionKey, BitSet frameCounter) { this.sessionKey = sessionKey; this.frameCounter = (BitSet) frameCounter.clone(); this.initialFrameCounter = (BitSet) frameCounter.clone(); registers.clear(); LFSR lfsr1 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); LFSR lfsr2 = new LFSR(22, 10, new int[] {20, 21}); LFSR lfsr3 = new LFSR(23, 10, new int[] {7, 20, 21, 22}); registers.add(lfsr1); registers.add(lfsr2); registers.add(lfsr3); registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter)); } /** * Re-initializes the key stream generator with the original session key * and frame counter. This method restores the generator to its initial * state. */ public void reInitialize() { this.initialize(sessionKey, initialFrameCounter); } /** * Generates the next key stream of bits. * * <p> * This method performs an initial set of clocking cycles and then retrieves * a key stream of the specified length. After generation, it re-initializes * the internal registers. * </p> * * @return a BitSet containing the generated key stream bits. */ public BitSet getNextKeyStream() { for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) { this.clock(); } BitSet result = new BitSet(KEY_STREAM_LENGTH); for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) { boolean outputBit = this.clock(); result.set(cycle - 1, outputBit); } reInitializeRegisters(); return result; } /** * Re-initializes the registers for the LFSRs. * * <p> * This method increments the frame counter and re-initializes each LFSR * with the current session key and frame counter. * </p> */ private void reInitializeRegisters() { incrementFrameCounter(); registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter)); } /** * Increments the current frame counter. * * <p> * This method uses a utility function to increment the frame counter, * which influences the key stream generation process. * </p> */ private void incrementFrameCounter() { Utils.increment(frameCounter, FRAME_COUNTER_LENGTH); } /** * Retrieves the current frame counter. * * @return a BitSet representing the current state of the frame counter. */ public BitSet getFrameCounter() { return frameCounter; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
src/main/java/com/thealgorithms/ciphers/a5/Utils.java
package com.thealgorithms.ciphers.a5; // Source // http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html // package com.java2s; // License from project: Open Source License import java.util.BitSet; public final class Utils { private Utils() { } public static boolean increment(BitSet bits, int size) { int i = size - 1; while (i >= 0 && bits.get(i)) { bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/ } if (i < 0) { return false; } bits.set(i, true); return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
package com.thealgorithms.ciphers.a5; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * The CompositeLFSR class represents a composite implementation of * Linear Feedback Shift Registers (LFSRs) for cryptographic purposes. * * <p> * This abstract class manages a collection of LFSR instances and * provides a mechanism for irregular clocking based on the * majority bit among the registers. It implements the BaseLFSR * interface, requiring subclasses to define specific LFSR behaviors. * </p> */ public abstract class CompositeLFSR implements BaseLFSR { protected final List<LFSR> registers = new ArrayList<>(); /** * Performs a clocking operation on the composite LFSR. * * <p> * This method determines the majority bit across all registers and * clocks each register based on its clock bit. If a register's * clock bit matches the majority bit, it is clocked (shifted). * The method also computes and returns the XOR of the last bits * of all registers. * </p> * * @return the XOR value of the last bits of all registers. */ @Override public boolean clock() { boolean majorityBit = getMajorityBit(); boolean result = false; for (var register : registers) { result ^= register.getLastBit(); if (register.getClockBit() == majorityBit) { register.clock(); } } return result; } /** * Calculates the majority bit among all registers. * * <p> * This private method counts the number of true and false clock bits * across all LFSR registers. It returns true if the count of true * bits is greater than or equal to the count of false bits; otherwise, * it returns false. * </p> * * @return true if the majority clock bits are true; false otherwise. */ private boolean getMajorityBit() { Map<Boolean, Integer> bitCount = new TreeMap<>(); bitCount.put(Boolean.FALSE, 0); bitCount.put(Boolean.TRUE, 0); registers.forEach(lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1)); return bitCount.get(Boolean.FALSE) <= bitCount.get(Boolean.TRUE); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
package com.thealgorithms.ciphers.a5; import java.util.BitSet; /** * The A5Cipher class implements the A5/1 stream cipher, which is a widely used * encryption algorithm, particularly in mobile communications. * * This implementation uses a key stream generator to produce a stream of bits * that are XORed with the plaintext bits to produce the ciphertext. * * <p> * For more details about the A5/1 algorithm, refer to * <a href="https://en.wikipedia.org/wiki/A5/1">Wikipedia</a>. * </p> */ public class A5Cipher { private final A5KeyStreamGenerator keyStreamGenerator; private static final int KEY_STREAM_LENGTH = 228; // Length of the key stream in bits (28.5 bytes) /** * Constructs an A5Cipher instance with the specified session key and frame counter. * * @param sessionKey a BitSet representing the session key used for encryption. * @param frameCounter a BitSet representing the frame counter that helps in key stream generation. */ public A5Cipher(BitSet sessionKey, BitSet frameCounter) { keyStreamGenerator = new A5KeyStreamGenerator(); keyStreamGenerator.initialize(sessionKey, frameCounter); } /** * Encrypts the given plaintext bits using the A5/1 cipher algorithm. * * This method generates a key stream and XORs it with the provided plaintext * bits to produce the ciphertext. * * @param plainTextBits a BitSet representing the plaintext bits to be encrypted. * @return a BitSet containing the encrypted ciphertext bits. */ public BitSet encrypt(BitSet plainTextBits) { // create a copy var result = new BitSet(KEY_STREAM_LENGTH); result.xor(plainTextBits); var key = keyStreamGenerator.getNextKeyStream(); result.xor(key); return result; } /** * Resets the internal counter of the key stream generator. * * This method can be called to re-initialize the state of the key stream * generator, allowing for new key streams to be generated for subsequent * encryptions. */ public void resetCounter() { keyStreamGenerator.reInitialize(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SelectionSort.java
src/main/java/com/thealgorithms/sorts/SelectionSort.java
package com.thealgorithms.sorts; public class SelectionSort implements SortAlgorithm { /** * Generic Selection Sort algorithm. * * Time Complexity: * - Best case: O(n^2) * - Average case: O(n^2) * - Worst case: O(n^2) * * Space Complexity: O(1) – in-place sorting. * * @see SortAlgorithm */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { for (int i = 0; i < array.length - 1; i++) { final int minIndex = findIndexOfMin(array, i); SortUtils.swap(array, i, minIndex); } return array; } private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int startIndex) { int minIndex = startIndex; for (int i = startIndex + 1; i < array.length; i++) { if (SortUtils.less(array[i], array[minIndex])) { minIndex = i; } } return minIndex; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public final class PigeonholeSort { private PigeonholeSort() { } /** * Sorts the given array using the pigeonhole sort algorithm. * * @param array the array to be sorted * @throws IllegalArgumentException if any negative integers are found * @return the sorted array */ public static int[] sort(int[] array) { checkForNegativeInput(array); if (array.length == 0) { return array; } final int maxElement = Arrays.stream(array).max().orElseThrow(); final List<List<Integer>> pigeonHoles = createPigeonHoles(maxElement); populatePigeonHoles(array, pigeonHoles); collectFromPigeonHoles(array, pigeonHoles); return array; } /** * Checks if the array contains any negative integers. * * @param array the array to be checked * @throws IllegalArgumentException if any negative integers are found */ private static void checkForNegativeInput(int[] array) { for (final int number : array) { if (number < 0) { throw new IllegalArgumentException("Array contains negative integers."); } } } /** * Creates pigeonholes for sorting using an ArrayList of ArrayLists. * * @param maxElement the maximum element in the array * @return an ArrayList of ArrayLists */ private static List<List<Integer>> createPigeonHoles(int maxElement) { List<List<Integer>> pigeonHoles = new ArrayList<>(maxElement + 1); for (int i = 0; i <= maxElement; i++) { pigeonHoles.add(new ArrayList<>()); } return pigeonHoles; } /** * Populates the pigeonholes with elements from the array. * * @param array the array to be sorted * @param pigeonHoles the pigeonholes to be populated */ private static void populatePigeonHoles(int[] array, List<List<Integer>> pigeonHoles) { for (int element : array) { pigeonHoles.get(element).add(element); } } /** * Collects sorted elements from the pigeonholes back into the array. * * @param array the array to be sorted * @param pigeonHoles the populated pigeonholes */ private static void collectFromPigeonHoles(int[] array, Iterable<List<Integer>> pigeonHoles) { int index = 0; for (final var pigeonHole : pigeonHoles) { for (final int element : pigeonHole) { array[index++] = element; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BucketSort.java
src/main/java/com/thealgorithms/sorts/BucketSort.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * BucketSort class provides a method to sort an array of elements using the Bucket Sort algorithm * and implements the SortAlgorithm interface. */ public class BucketSort implements SortAlgorithm { // Constant that defines the divisor for determining the number of buckets private static final int BUCKET_DIVISOR = 10; @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } T min = findMin(array); T max = findMax(array); int numberOfBuckets = calculateNumberOfBuckets(array.length); List<List<T>> buckets = initializeBuckets(numberOfBuckets); distributeElementsIntoBuckets(array, buckets, min, max, numberOfBuckets); return concatenateBuckets(buckets, array); } /** * Calculates the number of buckets to use based on the size of the array. * * @param arrayLength the length of the array * @return the number of buckets */ private int calculateNumberOfBuckets(final int arrayLength) { return Math.max(arrayLength / BUCKET_DIVISOR, 1); } /** * Initializes a list of empty buckets. * * @param numberOfBuckets the number of buckets to initialize * @param <T> the type of elements to be sorted * @return a list of empty buckets */ private <T extends Comparable<T>> List<List<T>> initializeBuckets(int numberOfBuckets) { List<List<T>> buckets = new ArrayList<>(numberOfBuckets); for (int i = 0; i < numberOfBuckets; i++) { buckets.add(new ArrayList<>()); } return buckets; } /** * Distributes elements from the array into the appropriate buckets. * * @param array the array of elements to distribute * @param buckets the list of buckets * @param min the minimum value in the array * @param max the maximum value in the array * @param numberOfBuckets the total number of buckets * @param <T> the type of elements in the array */ private <T extends Comparable<T>> void distributeElementsIntoBuckets(T[] array, List<List<T>> buckets, final T min, final T max, final int numberOfBuckets) { for (final T element : array) { int bucketIndex = hash(element, min, max, numberOfBuckets); buckets.get(bucketIndex).add(element); } } /** * Concatenates the sorted buckets back into the original array. * * @param buckets the list of sorted buckets * @param array the original array * @param <T> the type of elements in the array * @return the sorted array */ private <T extends Comparable<T>> T[] concatenateBuckets(Iterable<List<T>> buckets, T[] array) { int index = 0; for (List<T> bucket : buckets) { Collections.sort(bucket); for (T element : bucket) { array[index++] = element; } } return array; } /** * The method computes the index of the bucket in which a given element should be placed. * This is done by "normalizing" the element within the range of the array's minimum (min) and maximum (max) values, * and then mapping this normalized value to a specific bucket index. * * @param element the element of the array * @param min the minimum value in the array * @param max the maximum value in the array * @param numberOfBuckets the total number of buckets * @param <T> the type of elements in the array * @return the index of the bucket */ private <T extends Comparable<T>> int hash(final T element, final T min, final T max, final int numberOfBuckets) { double range = max.compareTo(min); double normalizedValue = element.compareTo(min) / range; return (int) (normalizedValue * (numberOfBuckets - 1)); } private <T extends Comparable<T>> T findMin(T[] array) { T min = array[0]; for (T element : array) { if (SortUtils.less(element, min)) { min = element; } } return min; } private <T extends Comparable<T>> T findMax(T[] array) { T max = array[0]; for (T element : array) { if (SortUtils.greater(element, max)) { max = element; } } return max; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java
src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java
package com.thealgorithms.sorts; import java.util.PriorityQueue; /** * Sorts an array using Java's PriorityQueue (Min-Heap). * * <p>Example: Input: [7, 2, 9, 4, 1] Output: [1, 2, 4, 7, 9] * * <p>Time Complexity: * - Inserting n elements into the PriorityQueue → O(n log n) * - Polling n elements → O(n log n) * - Total: O(n log n) * * <p>Space Complexity: O(n) for the PriorityQueue * * @see <a href="https://en.wikipedia.org/wiki/Heap_(data_structure)"> * Heap / PriorityQueue</a> */ public final class PriorityQueueSort { // Private constructor to prevent instantiation (utility class) private PriorityQueueSort() { } /** * Sorts the given array in ascending order using a PriorityQueue. * * @param arr the array to be sorted * @return the sorted array (in-place) */ public static int[] sort(int[] arr) { if (arr == null || arr.length == 0) { return arr; } PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : arr) { pq.offer(num); } int i = 0; while (!pq.isEmpty()) { arr[i++] = pq.poll(); } return arr; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/GnomeSort.java
src/main/java/com/thealgorithms/sorts/GnomeSort.java
package com.thealgorithms.sorts; /** * Implementation of gnome sort * * @author Podshivalov Nikita (https://github.com/nikitap492) * @since 2018-04-10 */ public class GnomeSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(final T[] array) { int i = 1; int j = 2; while (i < array.length) { if (SortUtils.less(array[i - 1], array[i])) { i = j++; } else { SortUtils.swap(array, i - 1, i); if (--i == 0) { i = j++; } } } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SwapSort.java
src/main/java/com/thealgorithms/sorts/SwapSort.java
package com.thealgorithms.sorts; /** * The idea of Swap-Sort is to count the number m of smaller values (that are in * A) from each element of an array A(1...n) and then swap the element with the * element in A(m+1). This ensures that the exchanged element is already in the * correct, i.e. final, position. The disadvantage of this algorithm is that * each element may only occur once, otherwise there is no termination. */ public class SwapSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { int index = 0; while (index < array.length - 1) { final int amountSmallerElements = this.getSmallerElementCount(array, index); if (amountSmallerElements > 0) { SortUtils.swap(array, index, index + amountSmallerElements); } else { index++; } } return array; } private <T extends Comparable<T>> int getSmallerElementCount(final T[] array, final int index) { int counter = 0; for (int i = index + 1; i < array.length; i++) { if (SortUtils.less(array[i], array[index])) { counter++; } } return counter; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/TreeSort.java
src/main/java/com/thealgorithms/sorts/TreeSort.java
package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.print; import com.thealgorithms.datastructures.trees.BSTRecursiveGeneric; import java.util.List; /** * <h1> Implementation of the Tree Sort algorithm</h1> * * <p> * Tree Sort: A sorting algorithm which constructs a Binary Search Tree using * the unsorted data and then outputs the data by inorder traversal of the tree. * * Reference: https://en.wikipedia.org/wiki/Tree_sort * </p> * * @author Madhur Panwar (https://github.com/mdrpanwar) */ public class TreeSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] unsortedArray) { return doTreeSortArray(unsortedArray); } @Override public <T extends Comparable<T>> List<T> sort(List<T> unsortedList) { return doTreeSortList(unsortedList); } private <T extends Comparable<T>> T[] doTreeSortArray(T[] unsortedArray) { // create a generic BST tree BSTRecursiveGeneric<T> tree = new BSTRecursiveGeneric<T>(); // add all elements to the tree for (T element : unsortedArray) { tree.add(element); } // get the sorted list by inorder traversal of the tree List<T> sortedList = tree.inorderSort(); // add the elements back to the initial array int i = 0; for (T element : sortedList) { unsortedArray[i++] = element; } // return the array return unsortedArray; } private <T extends Comparable<T>> List<T> doTreeSortList(Iterable<T> unsortedList) { // create a generic BST tree BSTRecursiveGeneric<T> tree = new BSTRecursiveGeneric<T>(); // add all elements to the tree for (T element : unsortedList) { tree.add(element); } // get the sorted list by inorder traversal of the tree and return it return tree.inorderSort(); } public static void main(String[] args) { TreeSort treeSort = new TreeSort(); // ==== Integer Array ======= System.out.println("Testing for Integer Array...."); Integer[] a = {3, -7, 45, 1, 343, -5, 2, 9}; System.out.printf("%-10s", "unsorted: "); print(a); a = treeSort.sort(a); System.out.printf("%-10s", "sorted: "); print(a); System.out.println(); // ==== Integer List ======= System.out.println("Testing for Integer List...."); List<Integer> intList = List.of(3, -7, 45, 1, 343, -5, 2, 9); System.out.printf("%-10s", "unsorted: "); print(intList); intList = treeSort.sort(intList); System.out.printf("%-10s", "sorted: "); print(intList); System.out.println(); // ==== String Array ======= System.out.println("Testing for String Array...."); String[] b = { "banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple", }; System.out.printf("%-10s", "unsorted: "); print(b); b = treeSort.sort(b); System.out.printf("%-10s", "sorted: "); print(b); System.out.println(); // ==== String List ======= System.out.println("Testing for String List...."); List<String> stringList = List.of("banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"); System.out.printf("%-10s", "unsorted: "); print(stringList); stringList = treeSort.sort(stringList); System.out.printf("%-10s", "sorted: "); print(stringList); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/CycleSort.java
src/main/java/com/thealgorithms/sorts/CycleSort.java
package com.thealgorithms.sorts; /** * This class implements the cycle sort algorithm. * Cycle sort is an in-place sorting algorithm, unstable, and efficient for scenarios with limited memory usage. * @author Podshivalov Nikita (https://github.com/nikitap492) */ class CycleSort implements SortAlgorithm { /** * Sorts an array of comparable elements using the cycle sort algorithm. * * @param <T> The type of elements in the array, which must be comparable * @param array The array to be sorted * @return The sorted array */ @Override public <T extends Comparable<T>> T[] sort(final T[] array) { final int length = array.length; for (int cycleStart = 0; cycleStart <= length - 2; cycleStart++) { T item = array[cycleStart]; int pos = findPosition(array, cycleStart, item); if (pos == cycleStart) { continue; // Item is already in the correct position } item = placeItem(array, item, pos); // Rotate the rest of the cycle while (pos != cycleStart) { pos = findPosition(array, cycleStart, item); item = placeItem(array, item, pos); } } return array; } /** * Finds the correct position for the given item starting from cycleStart. * * @param <T> The type of elements in the array, which must be comparable * @param array The array to be sorted * @param cycleStart The starting index of the cycle * @param item The item whose position is to be found * @return The correct position of the item */ private <T extends Comparable<T>> int findPosition(final T[] array, final int cycleStart, final T item) { int pos = cycleStart; for (int i = cycleStart + 1; i < array.length; i++) { if (SortUtils.less(array[i], item)) { pos++; } } return pos; } /** * Places the item in its correct position, handling duplicates, and returns the displaced item. * * @param <T> The type of elements in the array, which must be comparable * @param array The array being sorted * @param item The item to be placed * @param pos The position where the item is to be placed * @return The displaced item */ private <T extends Comparable<T>> T placeItem(final T[] array, final T item, int pos) { while (item.compareTo(array[pos]) == 0) { pos++; } return replace(array, pos, item); } /** * Replaces an element in the array with the given item and returns the replaced item. * * @param <T> The type of elements in the array, which must be comparable * @param array The array in which the replacement will occur * @param pos The position at which the replacement will occur * @param item The item to be placed in the array * @return The replaced item */ private <T extends Comparable<T>> T replace(final T[] array, final int pos, final T item) { final T replacedItem = array[pos]; array[pos] = item; return replacedItem; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/HeapSort.java
src/main/java/com/thealgorithms/sorts/HeapSort.java
package com.thealgorithms.sorts; /** * Heap Sort algorithm implementation. * * Heap sort converts the array into a max-heap and repeatedly extracts the maximum * element to sort the array in increasing order. * * Time Complexity: * - Best case: O(n log n) * - Average case: O(n log n) * - Worst case: O(n log n) * * Space Complexity: O(1) – in-place sorting * * @see <a href="https://en.wikipedia.org/wiki/Heapsort">Heap Sort Algorithm</a> * @see SortAlgorithm */ public class HeapSort implements SortAlgorithm { /** * For simplicity, we are considering the heap root index as 1 instead of 0. * This approach simplifies future calculations. As a result, we decrease * the indexes by 1 when calling {@link SortUtils#less(Comparable, Comparable)} * and provide adjusted values to the {@link SortUtils#swap(Object[], int, int)} methods. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { int n = array.length; heapify(array, n); while (n > 1) { SortUtils.swap(array, 0, n - 1); n--; siftDown(array, 1, n); } return array; } private <T extends Comparable<T>> void heapify(final T[] array, final int n) { for (int k = n / 2; k >= 1; k--) { siftDown(array, k, n); } } private <T extends Comparable<T>> void siftDown(final T[] array, int k, final int n) { while (2 * k <= n) { int j = 2 * k; if (j < n && SortUtils.less(array[j - 1], array[j])) { j++; } if (!SortUtils.less(array[k - 1], array[j - 1])) { break; } SortUtils.swap(array, k - 1, j - 1); k = j; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SortUtils.java
src/main/java/com/thealgorithms/sorts/SortUtils.java
package com.thealgorithms.sorts; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; final class SortUtils { private SortUtils() { } /** * Swaps two elements at the given positions in an array. * * @param array the array in which to swap elements * @param i the index of the first element to swap * @param j the index of the second element to swap * @param <T> the type of elements in the array */ public static <T> void swap(T[] array, int i, int j) { if (i != j) { final T temp = array[i]; array[i] = array[j]; array[j] = temp; } } /** * Compares two elements to see if the first is less than the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is less than the second, false otherwise */ public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) < 0; } /** * Compares two elements to see if the first is greater than the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is greater than the second, false otherwise */ public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) > 0; } /** * Compares two elements to see if the first is greater than or equal to the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is greater than or equal to the second, false otherwise */ static <T extends Comparable<T>> boolean greaterOrEqual(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) >= 0; } /** * Prints the elements of a list to standard output. * * @param listToPrint the list to print */ static void print(List<?> listToPrint) { String result = listToPrint.stream().map(Object::toString).collect(Collectors.joining(" ")); System.out.println(result); } /** * Prints the elements of an array to standard output. * * @param array the array to print */ static <T> void print(T[] array) { System.out.println(Arrays.toString(array)); } /** * Flips the order of elements in the specified range of an array. * * @param array the array whose elements are to be flipped * @param left the left boundary of the range to be flipped (inclusive) * @param right the right boundary of the range to be flipped (inclusive) */ public static <T extends Comparable<T>> void flip(T[] array, int left, int right) { while (left <= right) { swap(array, left++, right--); } } /** * Checks whether the array is sorted in ascending order. * * @param array the array to check * @return true if the array is sorted in ascending order, false otherwise */ public static <T extends Comparable<T>> boolean isSorted(T[] array) { for (int i = 1; i < array.length; i++) { if (less(array[i], array[i - 1])) { return false; } } return true; } /** * Checks whether the list is sorted in ascending order. * * @param list the list to check * @return true if the list is sorted in ascending order, false otherwise */ public static <T extends Comparable<T>> boolean isSorted(List<T> list) { for (int i = 1; i < list.size(); i++) { if (less(list.get(i), list.get(i - 1))) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
package com.thealgorithms.sorts; import java.util.Arrays; /** * Implementation of Merge Sort without using extra space for merging. * This implementation performs in-place merging to sort the array of integers. */ public final class MergeSortNoExtraSpace { private MergeSortNoExtraSpace() { } /** * Sorts the array using in-place merge sort algorithm. * * @param array the array to be sorted * @return the sorted array * @throws IllegalArgumentException If the array contains negative numbers. */ public static int[] sort(int[] array) { if (array.length == 0) { return array; } if (Arrays.stream(array).anyMatch(s -> s < 0)) { throw new IllegalArgumentException("Implementation cannot sort negative numbers."); } final int maxElement = Arrays.stream(array).max().getAsInt() + 1; mergeSort(array, 0, array.length - 1, maxElement); return array; } /** * Recursively divides the array into two halves, sorts and merges them. * * @param array the array to be sorted * @param start the starting index of the array * @param end the ending index of the array * @param maxElement the value greater than any element in the array, used for encoding */ public static void mergeSort(int[] array, int start, int end, int maxElement) { if (start < end) { final int middle = (start + end) >>> 1; mergeSort(array, start, middle, maxElement); mergeSort(array, middle + 1, end, maxElement); merge(array, start, middle, end, maxElement); } } /** * Merges two sorted subarrays [start...middle] and [middle+1...end] in place. * * @param array the array containing the subarrays to be merged * @param start the starting index of the first subarray * @param middle the ending index of the first subarray and starting index of the second subarray * @param end the ending index of the second subarray * @param maxElement the value greater than any element in the array, used for encoding */ private static void merge(int[] array, int start, int middle, int end, int maxElement) { int i = start; int j = middle + 1; int k = start; while (i <= middle && j <= end) { if (array[i] % maxElement <= array[j] % maxElement) { array[k] = array[k] + (array[i] % maxElement) * maxElement; k++; i++; } else { array[k] = array[k] + (array[j] % maxElement) * maxElement; k++; j++; } } while (i <= middle) { array[k] = array[k] + (array[i] % maxElement) * maxElement; k++; i++; } while (j <= end) { array[k] = array[k] + (array[j] % maxElement) * maxElement; k++; j++; } for (i = start; i <= end; i++) { array[i] = array[i] / maxElement; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/StrandSort.java
src/main/java/com/thealgorithms/sorts/StrandSort.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * StrandSort class implementing the SortAlgorithm interface using arrays. */ public final class StrandSort implements SortAlgorithm { /** * Sorts the given array using the Strand Sort algorithm. * * @param <T> The type of elements to be sorted, must be Comparable. * @param array The array to be sorted. * @return The sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { List<T> unsortedList = new ArrayList<>(Arrays.asList(array)); List<T> sortedList = strandSort(unsortedList); return sortedList.toArray(array); } /** * Strand Sort algorithm that sorts a list. * * @param <T> The type of elements to be sorted, must be Comparable. * @param list The list to be sorted. * @return The sorted list. */ private static <T extends Comparable<? super T>> List<T> strandSort(List<T> list) { if (list.size() <= 1) { return list; } List<T> result = new ArrayList<>(); while (!list.isEmpty()) { final List<T> sorted = new ArrayList<>(); sorted.add(list.removeFirst()); for (int i = 0; i < list.size();) { if (sorted.getLast().compareTo(list.get(i)) <= 0) { sorted.add(list.remove(i)); } else { i++; } } result = merge(result, sorted); } return result; } /** * Merges two sorted lists into one sorted list. * * @param <T> The type of elements to be sorted, must be Comparable. * @param left The first sorted list. * @param right The second sorted list. * @return The merged sorted list. */ private static <T extends Comparable<? super T>> List<T> merge(List<T> left, List<T> right) { List<T> result = new ArrayList<>(); int i = 0; int j = 0; while (i < left.size() && j < right.size()) { if (left.get(i).compareTo(right.get(j)) <= 0) { result.add(left.get(i)); i++; } else { result.add(right.get(j)); j++; } } result.addAll(left.subList(i, left.size())); result.addAll(right.subList(j, right.size())); return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/OddEvenSort.java
src/main/java/com/thealgorithms/sorts/OddEvenSort.java
package com.thealgorithms.sorts; /** * OddEvenSort class implements the SortAlgorithm interface using the odd-even sort technique. * Odd-even sort is a comparison sort related to bubble sort. * It operates by comparing all (odd, even)-indexed pairs of adjacent elements in the list and, if a pair is in the wrong order, swapping them. * The next step repeats this process for (even, odd)-indexed pairs. This process continues until the list is sorted. * */ public final class OddEvenSort implements SortAlgorithm { /** * Sorts the given array using the Odd-Even Sort algorithm. * * @param <T> the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { boolean sorted = false; while (!sorted) { sorted = performOddSort(array); sorted = performEvenSort(array) && sorted; } return array; } private <T extends Comparable<T>> boolean performOddSort(T[] array) { boolean sorted = true; for (int i = 1; i < array.length - 1; i += 2) { if (SortUtils.greater(array[i], array[i + 1])) { SortUtils.swap(array, i, i + 1); sorted = false; } } return sorted; } private <T extends Comparable<T>> boolean performEvenSort(T[] array) { boolean sorted = true; for (int i = 0; i < array.length - 1; i += 2) { if (SortUtils.greater(array[i], array[i + 1])) { SortUtils.swap(array, i, i + 1); sorted = false; } } return sorted; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java
src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java
package com.thealgorithms.sorts; /** * BinaryInsertionSort class implements the SortAlgorithm interface using the binary insertion sort technique. * Binary Insertion Sort improves upon the simple insertion sort by using binary search to find the appropriate * location to insert the new element, reducing the number of comparisons in the insertion step. */ public class BinaryInsertionSort implements SortAlgorithm { /** * Sorts the given array using the Binary Insertion Sort algorithm. * * @param <T> the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ public <T extends Comparable<T>> T[] sort(T[] array) { for (int i = 1; i < array.length; i++) { final T temp = array[i]; int low = 0; int high = i - 1; while (low <= high) { final int mid = (low + high) >>> 1; if (SortUtils.less(temp, array[mid])) { high = mid - 1; } else { low = mid + 1; } } for (int j = i; j >= low + 1; j--) { array[j] = array[j - 1]; } array[low] = temp; } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java
src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java
package com.thealgorithms.sorts; /** * Introspective Sort Algorithm Implementation * * @see <a href="https://en.wikipedia.org/wiki/Introsort">IntroSort Algorithm</a> */ public class IntrospectiveSort implements SortAlgorithm { private static final int INSERTION_SORT_THRESHOLD = 16; /** * Sorts the given array using Introspective Sort, which combines quicksort, heapsort, and insertion sort. * * @param array The array to be sorted * @param <T> The type of elements in the array, which must be comparable * @return The sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array == null || array.length <= 1) { return array; } final int depth = 2 * (int) (Math.log(array.length) / Math.log(2)); introspectiveSort(array, 0, array.length - 1, depth); return array; } /** * Performs introspective sort on the specified subarray. * * @param array The array to be sorted * @param low The starting index of the subarray * @param high The ending index of the subarray * @param depth The current depth of recursion * @param <T> The type of elements in the array, which must be comparable */ private static <T extends Comparable<T>> void introspectiveSort(T[] array, final int low, int high, final int depth) { while (high - low > INSERTION_SORT_THRESHOLD) { if (depth == 0) { heapSort(array, low, high); return; } final int pivotIndex = partition(array, low, high); introspectiveSort(array, pivotIndex + 1, high, depth - 1); high = pivotIndex - 1; } insertionSort(array, low, high); } /** * Partitions the array around a pivot. * * @param array The array to be partitioned * @param low The starting index of the subarray * @param high The ending index of the subarray * @param <T> The type of elements in the array, which must be comparable * @return The index of the pivot */ private static <T extends Comparable<T>> int partition(T[] array, final int low, final int high) { final int pivotIndex = low + (int) (Math.random() * (high - low + 1)); SortUtils.swap(array, pivotIndex, high); final T pivot = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (SortUtils.greaterOrEqual(pivot, array[j])) { i++; SortUtils.swap(array, i, j); } } SortUtils.swap(array, i + 1, high); return i + 1; } /** * Sorts a subarray using insertion sort. * * @param array The array to be sorted * @param low The starting index of the subarray * @param high The ending index of the subarray * @param <T> The type of elements in the array, which must be comparable */ private static <T extends Comparable<T>> void insertionSort(T[] array, final int low, final int high) { for (int i = low + 1; i <= high; i++) { final T key = array[i]; int j = i - 1; while (j >= low && SortUtils.greater(array[j], key)) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } } /** * Sorts a subarray using heapsort. * * @param array The array to be sorted * @param low The starting index of the subarray * @param high The ending index of the subarray * @param <T> The type of elements in the array, which must be comparable */ private static <T extends Comparable<T>> void heapSort(T[] array, final int low, final int high) { final int n = high - low + 1; for (int i = (n / 2) - 1; i >= 0; i--) { heapify(array, i, n, low); } for (int i = high; i > low; i--) { SortUtils.swap(array, low, i); heapify(array, 0, i - low, low); } } /** * Maintains the heap property for a subarray. * * @param array The array to be heapified * @param i The index to be heapified * @param n The size of the heap * @param low The starting index of the subarray * @param <T> The type of elements in the array, which must be comparable */ private static <T extends Comparable<T>> void heapify(T[] array, final int i, final int n, final int low) { final int left = 2 * i + 1; final int right = 2 * i + 2; int largest = i; if (left < n && SortUtils.greater(array[low + left], array[low + largest])) { largest = left; } if (right < n && SortUtils.greater(array[low + right], array[low + largest])) { largest = right; } if (largest != i) { SortUtils.swap(array, low + i, low + largest); heapify(array, largest, n, low); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
src/main/java/com/thealgorithms/sorts/TopologicalSort.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; /** * The Topological Sorting algorithm linearly orders a DAG or Directed Acyclic Graph into * a linked list. A Directed Graph is proven to be acyclic when a DFS or Depth First Search is * performed, yielding no back-edges. * * Time Complexity: O(V + E) * - V: number of vertices * - E: number of edges * * Space Complexity: O(V + E) * - adjacency list and recursion stack in DFS * * Reference: https://en.wikipedia.org/wiki/Topological_sorting * * Author: Jonathan Taylor (https://github.com/Jtmonument) * Based on Introduction to Algorithms 3rd Edition */ public final class TopologicalSort { private TopologicalSort() { } /* * Enum to represent the colors for the depth first search * */ private enum Color { WHITE, GRAY, BLACK, } /* * Class to represent vertices * */ private static class Vertex { /* * Name of vertex * */ public final String label; /* * Represents the category of visit in DFS * */ public Color color = Color.WHITE; /* * The array of names of descendant vertices * */ public final ArrayList<String> next = new ArrayList<>(); Vertex(String label) { this.label = label; } } /* * Graph class uses the adjacency list representation * */ static class Graph { /* * Adjacency list representation * */ private final HashMap<String, Vertex> adj = new LinkedHashMap<>(); /* * Function to add an edge to the graph * */ public void addEdge(String label, String... next) { adj.put(label, new Vertex(label)); if (!next[0].isEmpty()) { Collections.addAll(adj.get(label).next, next); } } } /* * Depth First Search * * DFS(G) * for each vertex u ∈ G.V * u.color = WHITE * u.π = NIL * time = 0 * for each vertex u ∈ G.V * if u.color == WHITE * DFS-VISIT(G, u) * * Performed in Θ(V + E) time * */ public static LinkedList<String> sort(Graph graph) { LinkedList<String> list = new LinkedList<>(); graph.adj.forEach((name, vertex) -> { if (vertex.color == Color.WHITE) { list.addFirst(sort(graph, vertex, list)); } }); return list; } /* * Depth First Search Visit * * DFS-Visit(G, u) * time = time + 1 * u.d = time * u.color = GRAY * for each v ∈ G.Adj[u] * if v.color == WHITE * v.π = u * DFS-Visit(G, u) * u.color = BLACK * time = time + 1 * u.f = time * */ private static String sort(Graph graph, Vertex u, LinkedList<String> list) { u.color = Color.GRAY; graph.adj.get(u.label).next.forEach(label -> { if (graph.adj.get(label).color == Color.WHITE) { list.addFirst(sort(graph, graph.adj.get(label), list)); } else if (graph.adj.get(label).color == Color.GRAY) { /* * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f * * In many cases, we will not know u.f, but v.color denotes the type of edge * */ throw new RuntimeException("This graph contains a cycle. No linear ordering is possible. Back edge: " + u.label + " -> " + label); } }); u.color = Color.BLACK; return u.label; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
package com.thealgorithms.sorts; /** * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined * by a value given as the indented middle. First permutation: values less than middle. Second * permutation: values equal middle. Third permutation: values greater than middle. If no indented * middle is given, this implementation will use a value from the given Array. This value is the one * positioned in the arrays' middle if the arrays' length is odd. If the arrays' length is even, the * value left to the middle will be used. More information and Pseudocode: * https://en.wikipedia.org/wiki/Dutch_national_flag_problem */ public class DutchNationalFlagSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { return dutchNationalFlagSort(array, array[(int) Math.ceil((array.length) / 2.0) - 1]); } public <T extends Comparable<T>> T[] sort(T[] array, T intendedMiddle) { return dutchNationalFlagSort(array, intendedMiddle); } private <T extends Comparable<T>> T[] dutchNationalFlagSort(final T[] array, final T intendedMiddle) { int i = 0; int j = 0; int k = array.length - 1; while (j <= k) { if (SortUtils.less(array[j], intendedMiddle)) { SortUtils.swap(array, i, j); j++; i++; } else if (SortUtils.greater(array[j], intendedMiddle)) { SortUtils.swap(array, j, k); k--; } else { j++; } } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BogoSort.java
src/main/java/com/thealgorithms/sorts/BogoSort.java
package com.thealgorithms.sorts; import java.util.Random; /** * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ public class BogoSort implements SortAlgorithm { private static final Random RANDOM = new Random(); private static <T extends Comparable<T>> boolean isSorted(T[] array) { for (int i = 0; i < array.length - 1; i++) { if (SortUtils.less(array[i + 1], array[i])) { return false; } } return true; } // Randomly shuffles the array private static <T> void nextPermutation(T[] array) { int length = array.length; for (int i = 0; i < array.length; i++) { int randomIndex = i + RANDOM.nextInt(length - i); SortUtils.swap(array, randomIndex, i); } } public <T extends Comparable<T>> T[] sort(T[] array) { while (!isSorted(array)) { nextPermutation(array); } return array; } // Driver Program public static void main(String[] args) { // Integer Input Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; BogoSort bogoSort = new BogoSort(); // print a sorted array SortUtils.print(bogoSort.sort(integers)); // String Input String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(bogoSort.sort(strings)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/InsertionSort.java
src/main/java/com/thealgorithms/sorts/InsertionSort.java
package com.thealgorithms.sorts; /** * Generic Insertion Sort algorithm. * * Standard insertion sort iterates through the array and inserts each element into its * correct position in the sorted portion of the array. * * Sentinel sort is a variation that first places the minimum element at index 0 to * avoid redundant comparisons in subsequent passes. * * Time Complexity: * - Best case: O(n) – array is already sorted (sentinel sort can improve slightly) * - Average case: O(n^2) * - Worst case: O(n^2) – array is reverse sorted * * Space Complexity: O(1) – in-place sorting * * @see SortAlgorithm */ class InsertionSort implements SortAlgorithm { /** * Sorts the given array using the standard Insertion Sort algorithm. * * @param array The array to be sorted * @param <T> The type of elements in the array, which must be comparable * @return The sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { return sort(array, 0, array.length); } /** * Sorts a subarray of the given array using the standard Insertion Sort algorithm. * * @param array The array to be sorted * @param lo The starting index of the subarray * @param hi The ending index of the subarray (exclusive) * @param <T> The type of elements in the array, which must be comparable * @return The sorted array */ public <T extends Comparable<T>> T[] sort(T[] array, final int lo, final int hi) { if (array == null || lo >= hi) { return array; } for (int i = lo + 1; i < hi; i++) { final T key = array[i]; int j = i - 1; while (j >= lo && SortUtils.less(key, array[j])) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } return array; } /** * Sentinel sort is a function which on the first step finds the minimal element in the provided * array and puts it to the zero position, such a trick gives us an ability to avoid redundant * comparisons like `j > 0` and swaps (we can move elements on position right, until we find * the right position for the chosen element) on further step. * * @param array The array to be sorted * @param <T> The type of elements in the array, which must be comparable * @return The sorted array */ public <T extends Comparable<T>> T[] sentinelSort(T[] array) { if (array == null || array.length <= 1) { return array; } final int minElemIndex = findMinIndex(array); SortUtils.swap(array, 0, minElemIndex); for (int i = 2; i < array.length; i++) { final T currentValue = array[i]; int j = i; while (j > 0 && SortUtils.less(currentValue, array[j - 1])) { array[j] = array[j - 1]; j--; } array[j] = currentValue; } return array; } /** * Finds the index of the minimum element in the array. * * @param array The array to be searched * @param <T> The type of elements in the array, which must be comparable * @return The index of the minimum element */ private <T extends Comparable<T>> int findMinIndex(final T[] array) { int minIndex = 0; for (int i = 1; i < array.length; i++) { if (SortUtils.less(array[i], array[minIndex])) { minIndex = i; } } return minIndex; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java
src/main/java/com/thealgorithms/sorts/SortAlgorithm.java
package com.thealgorithms.sorts; import java.util.Arrays; import java.util.List; /** * The common interface of most sorting algorithms * * @author Podshivalov Nikita (https://github.com/nikitap492) */ @SuppressWarnings("rawtypes") public interface SortAlgorithm { /** * Main method arrays sorting algorithms * * @param unsorted - an array should be sorted * @return a sorted array */ <T extends Comparable<T>> T[] sort(T[] unsorted); /** * Auxiliary method for algorithms what wanted to work with lists from JCF * * @param unsorted - a list should be sorted * @return a sorted list */ @SuppressWarnings("unchecked") default<T extends Comparable<T>> List<T> sort(List<T> unsorted) { return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/TimSort.java
src/main/java/com/thealgorithms/sorts/TimSort.java
package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.less; /** * This is simplified TimSort algorithm implementation. The original one is more complicated. * <p> * For more details @see <a href="https://en.wikipedia.org/wiki/Timsort">TimSort Algorithm</a> */ @SuppressWarnings({"rawtypes", "unchecked"}) class TimSort implements SortAlgorithm { private static final int SUB_ARRAY_SIZE = 32; private Comparable[] aux; @Override public <T extends Comparable<T>> T[] sort(T[] array) { final int n = array.length; InsertionSort insertionSort = new InsertionSort(); for (int i = 0; i < n; i += SUB_ARRAY_SIZE) { insertionSort.sort(array, i, Math.min(i + SUB_ARRAY_SIZE, n)); } aux = new Comparable[n]; for (int sz = SUB_ARRAY_SIZE; sz < n; sz = sz + sz) { for (int lo = 0; lo < n - sz; lo += sz + sz) { merge(array, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, n - 1)); } } return array; } private <T extends Comparable<T>> void merge(T[] a, final int lo, final int mid, final int hi) { int i = lo; int j = mid + 1; System.arraycopy(a, lo, aux, lo, hi + 1 - lo); for (int k = lo; k <= hi; k++) { if (j > hi) { a[k] = (T) aux[i++]; } else if (i > mid) { a[k] = (T) aux[j++]; } else if (less(aux[j], aux[i])) { a[k] = (T) aux[j++]; } else { a[k] = (T) aux[i++]; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/CircleSort.java
src/main/java/com/thealgorithms/sorts/CircleSort.java
package com.thealgorithms.sorts; public class CircleSort implements SortAlgorithm { /* This method implements the circle sort * @param array The array to be sorted */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } while (doSort(array, 0, array.length - 1)) { } return array; } /** * Recursively sorts the array in a circular manner by comparing elements * from the start and end of the current segment. * * @param <T> The type of elements in the array, which must be comparable * @param array The array to be sorted * @param left The left boundary of the current segment being sorted * @param right The right boundary of the current segment being sorted * @return true if any elements were swapped during the sort; false otherwise */ private <T extends Comparable<T>> boolean doSort(final T[] array, final int left, final int right) { boolean swapped = false; if (left == right) { return false; } int low = left; int high = right; while (low < high) { if (SortUtils.greater(array[low], array[high])) { SortUtils.swap(array, low, high); swapped = true; } low++; high--; } if (low == high && SortUtils.greater(array[low], array[high + 1])) { SortUtils.swap(array, low, high + 1); swapped = true; } final int mid = left + (right - left) / 2; final boolean leftHalfSwapped = doSort(array, left, mid); final boolean rightHalfSwapped = doSort(array, mid + 1, right); return swapped || leftHalfSwapped || rightHalfSwapped; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/StalinSort.java
src/main/java/com/thealgorithms/sorts/StalinSort.java
package com.thealgorithms.sorts; public class StalinSort implements SortAlgorithm { @SuppressWarnings("unchecked") public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } int currentIndex = 0; for (int i = 1; i < array.length; i++) { if (SortUtils.greaterOrEqual(array[i], array[currentIndex])) { currentIndex++; array[currentIndex] = array[i]; } } // Create a result array with sorted elements T[] result = (T[]) java.lang.reflect.Array.newInstance(array.getClass().getComponentType(), currentIndex + 1); System.arraycopy(array, 0, result, 0, currentIndex + 1); return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/AdaptiveMergeSort.java
src/main/java/com/thealgorithms/sorts/AdaptiveMergeSort.java
package com.thealgorithms.sorts; public class AdaptiveMergeSort implements SortAlgorithm { @SuppressWarnings("unchecked") public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length <= 1) { return array; } T[] aux = array.clone(); sort(array, aux, 0, array.length - 1); return array; } private <T extends Comparable<T>> void sort(T[] array, T[] aux, int low, int high) { if (low >= high) { return; } int mid = low + (high - low) / 2; sort(array, aux, low, mid); sort(array, aux, mid + 1, high); merge(array, aux, low, mid, high); } private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) { System.arraycopy(array, low, aux, low, high - low + 1); int i = low; int j = mid + 1; for (int k = low; k <= high; k++) { if (i > mid) { array[k] = aux[j++]; } else if (j > high) { array[k] = aux[i++]; } else if (SortUtils.less(aux[j], aux[i])) { array[k] = aux[j++]; } else { array[k] = aux[i++]; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java
src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java
package com.thealgorithms.sorts; import java.util.Random; public final class SortUtilsRandomGenerator { private SortUtilsRandomGenerator() { } private static final Random RANDOM; private static final long SEED; static { SEED = System.currentTimeMillis(); RANDOM = new Random(SEED); } /** * Function to generate array of double values, with predefined size. * * @param size result array size * @return array of Double values, randomly generated, each element is between [0, 1) */ public static Double[] generateArray(int size) { Double[] arr = new Double[size]; for (int i = 0; i < size; i++) { arr[i] = generateDouble(); } return arr; } /** * Function to generate Double value. * * @return Double value [0, 1) */ public static Double generateDouble() { return RANDOM.nextDouble(); } /** * Function to generate int value. * * @return int value [0, n) */ public static int generateInt(int n) { return RANDOM.nextInt(n); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BitonicSort.java
src/main/java/com/thealgorithms/sorts/BitonicSort.java
package com.thealgorithms.sorts; import java.util.Arrays; import java.util.function.BiPredicate; /** * BitonicSort class implements the SortAlgorithm interface using the bitonic sort technique. */ public class BitonicSort implements SortAlgorithm { private enum Direction { DESCENDING, ASCENDING, } /** * Sorts the given array using the Bitonic Sort algorithm. * * @param <T> the type of elements in the array, which must implement the Comparable interface * @param array the array to be sorted * @return the sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } final int paddedSize = nextPowerOfTwo(array.length); T[] paddedArray = Arrays.copyOf(array, paddedSize); // Fill the padded part with a maximum value final T maxValue = max(array); Arrays.fill(paddedArray, array.length, paddedSize, maxValue); bitonicSort(paddedArray, 0, paddedSize, Direction.ASCENDING); return Arrays.copyOf(paddedArray, array.length); } private <T extends Comparable<T>> void bitonicSort(final T[] array, final int low, final int cnt, final Direction direction) { if (cnt > 1) { final int k = cnt / 2; // Sort first half in ascending order bitonicSort(array, low, k, Direction.ASCENDING); // Sort second half in descending order bitonicSort(array, low + k, cnt - k, Direction.DESCENDING); // Merge the whole sequence in ascending order bitonicMerge(array, low, cnt, direction); } } /** * Merges the bitonic sequence in the specified direction. * * @param <T> the type of elements in the array, which must be Comparable * @param array the array containing the bitonic sequence to be merged * @param low the starting index of the sequence to be merged * @param cnt the number of elements in the sequence to be merged * @param direction the direction of sorting */ private <T extends Comparable<T>> void bitonicMerge(T[] array, int low, int cnt, Direction direction) { if (cnt > 1) { final int k = cnt / 2; final BiPredicate<T, T> areSorted = (direction == Direction.ASCENDING) ? (a, b) -> SortUtils.less(a, b) : (a, b) -> SortUtils.greater(a, b); for (int i = low; i < low + k; i++) { if (!areSorted.test(array[i], array[i + k])) { SortUtils.swap(array, i, i + k); } } bitonicMerge(array, low, k, direction); bitonicMerge(array, low + k, cnt - k, direction); } } /** * Finds the next power of two greater than or equal to the given number. * * @param n the number * @return the next power of two */ private static int nextPowerOfTwo(int n) { int count = 0; // First n in the below condition is for the case where n is 0 if ((n & (n - 1)) == 0) { return n; } while (n != 0) { n >>= 1; count += 1; } return 1 << count; } /** * Finds the maximum element in the given array. * * @param <T> the type of elements in the array, which must implement the Comparable interface * @param array the array to be searched * @return the maximum element in the array * @throws IllegalArgumentException if the array is null or empty */ private static <T extends Comparable<T>> T max(final T[] array) { return Arrays.stream(array).max(Comparable::compareTo).orElseThrow(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/WaveSort.java
src/main/java/com/thealgorithms/sorts/WaveSort.java
package com.thealgorithms.sorts; /** * The WaveSort algorithm sorts an array so that every alternate element is greater than its adjacent elements. * This implementation also provides a method to check if an array is wave sorted. */ public class WaveSort implements SortAlgorithm { /** * Sorts the given array such that every alternate element is greater than its adjacent elements. * * @param array The array to be sorted. * @param <T> The type of elements in the array, which must be Comparable. * @return The sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { for (int i = 0; i < array.length; i += 2) { if (i > 0 && SortUtils.less(array[i], array[i - 1])) { SortUtils.swap(array, i, i - 1); } if (i < array.length - 1 && SortUtils.less(array[i], array[i + 1])) { SortUtils.swap(array, i, i + 1); } } return array; } /** * Checks if the given array is wave sorted. An array is wave sorted if every alternate element is greater than its adjacent elements. * * @param array The array to check. * @param <T> The type of elements in the array, which must be Comparable. * @return true if the array is wave sorted, false otherwise. */ public <T extends Comparable<T>> boolean isWaveSorted(T[] array) { for (int i = 0; i < array.length; i += 2) { if (i > 0 && SortUtils.less(array[i], array[i - 1])) { return false; } if (i < array.length - 1 && SortUtils.less(array[i], array[i + 1])) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/CountingSort.java
src/main/java/com/thealgorithms/sorts/CountingSort.java
package com.thealgorithms.sorts; import java.util.Arrays; /** * A standard implementation of the Counting Sort algorithm for integer arrays. * This implementation has a time complexity of O(n + k), where n is the number * of elements in the input array and k is the range of the input. * It works only with integer arrays. * * The space complexity is O(k), where k is the range of the input integers. * * Note: This implementation handles negative integers as it * calculates the range based on the minimum and maximum values of the array. * */ public final class CountingSort { private CountingSort() { } /** * Sorts an array of integers using the Counting Sort algorithm. * * @param array the array to be sorted * @return the sorted array */ public static int[] sort(int[] array) { if (array.length == 0) { return array; } final var stats = Arrays.stream(array).summaryStatistics(); final int min = stats.getMin(); int[] count = computeHistogram(array, min, stats.getMax() - min + 1); toCumulative(count); return reconstructSorted(count, min, array); } private static int[] computeHistogram(final int[] array, final int shift, final int spread) { int[] res = new int[spread]; for (final var value : array) { res[value - shift]++; } return res; } private static void toCumulative(int[] count) { for (int i = 1; i < count.length; i++) { count[i] += count[i - 1]; } } private static int[] reconstructSorted(final int[] cumulativeCount, final int shift, final int[] array) { int[] res = new int[array.length]; for (int i = array.length - 1; i >= 0; i--) { res[cumulativeCount[array[i] - shift] - 1] = array[i]; cumulativeCount[array[i] - shift]--; } return res; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SpreadSort.java
src/main/java/com/thealgorithms/sorts/SpreadSort.java
package com.thealgorithms.sorts; import java.util.Arrays; /** * SpreadSort is a highly efficient sorting algorithm suitable for large datasets. * It distributes elements into buckets and recursively sorts these buckets. * This implementation is generic and can sort any array of elements that extend Comparable. */ @SuppressWarnings("rawtypes") public class SpreadSort implements SortAlgorithm { private static final int MAX_INSERTION_SORT_THRESHOLD = 1000; private static final int MAX_INITIAL_BUCKET_CAPACITY = 1000; private static final int MAX_MIN_BUCKETS = 100; private final int insertionSortThreshold; private final int initialBucketCapacity; private final int minBuckets; /** * Constructor to initialize the SpreadSort algorithm with custom parameters. * * @param insertionSortThreshold the threshold for using insertion sort for small segments (1-1000) * @param initialBucketCapacity the initial capacity for each bucket (1-1000) * @param minBuckets the minimum number of buckets to use (1-100) */ public SpreadSort(int insertionSortThreshold, int initialBucketCapacity, int minBuckets) { if (insertionSortThreshold < 1 || insertionSortThreshold > MAX_INSERTION_SORT_THRESHOLD) { throw new IllegalArgumentException("Insertion sort threshold must be between 1 and " + MAX_INSERTION_SORT_THRESHOLD); } if (initialBucketCapacity < 1 || initialBucketCapacity > MAX_INITIAL_BUCKET_CAPACITY) { throw new IllegalArgumentException("Initial bucket capacity must be between 1 and " + MAX_INITIAL_BUCKET_CAPACITY); } if (minBuckets < 1 || minBuckets > MAX_MIN_BUCKETS) { throw new IllegalArgumentException("Minimum number of buckets must be between 1 and " + MAX_MIN_BUCKETS); } this.insertionSortThreshold = insertionSortThreshold; this.initialBucketCapacity = initialBucketCapacity; this.minBuckets = minBuckets; } /** * Default constructor with predefined values. */ public SpreadSort() { this(16, 16, 2); } /** * Sorts an array using the SpreadSort algorithm. * * @param array the array to be sorted * @param <T> the type of elements in the array * @return the sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } spreadSort(array, 0, array.length - 1); return array; } /** * Internal method to sort an array segment using the SpreadSort algorithm. * * @param array the array to be sorted * @param left the left boundary of the segment * @param right the right boundary of the segment * @param <T> the type of elements in the array */ private <T extends Comparable<T>> void spreadSort(final T[] array, final int left, final int right) { if (left >= right) { return; } // Base case for small segments if (right - left < insertionSortThreshold) { insertionSort(array, left, right); return; } T min = findMin(array, left, right); T max = findMax(array, left, right); if (min.equals(max)) { return; // All elements are the same } int numBuckets = calculateNumBuckets(right - left + 1); final Bucket<T>[] buckets = createBuckets(numBuckets); distributeElements(array, left, right, min, max, numBuckets, buckets); collectElements(array, left, buckets); } /** * Finds the minimum element in the specified segment of the array. * * @param array the array to search * @param left the left boundary of the segment * @param right the right boundary of the segment * @param <T> the type of elements in the array * @return the minimum element */ private <T extends Comparable<T>> T findMin(final T[] array, final int left, final int right) { T min = array[left]; for (int i = left + 1; i <= right; i++) { if (SortUtils.less(array[i], min)) { min = array[i]; } } return min; } /** * Finds the maximum element in the specified segment of the array. * * @param array the array to search * @param left the left boundary of the segment * @param right the right boundary of the segment * @param <T> the type of elements in the array * @return the maximum element */ private <T extends Comparable<T>> T findMax(final T[] array, final int left, final int right) { T max = array[left]; for (int i = left + 1; i <= right; i++) { if (SortUtils.greater(array[i], max)) { max = array[i]; } } return max; } /** * Calculates the number of buckets needed based on the size of the segment. * * @param segmentSize the size of the segment * @return the number of buckets */ private int calculateNumBuckets(final int segmentSize) { int numBuckets = segmentSize / insertionSortThreshold; return Math.max(numBuckets, minBuckets); } /** * Creates an array of buckets. * * @param numBuckets the number of buckets to create * @param <T> the type of elements in the buckets * @return an array of buckets */ @SuppressWarnings("unchecked") private <T extends Comparable<T>> Bucket<T>[] createBuckets(final int numBuckets) { final Bucket<T>[] buckets = new Bucket[numBuckets]; for (int i = 0; i < numBuckets; i++) { buckets[i] = new Bucket<>(initialBucketCapacity); } return buckets; } /** * Distributes elements of the array segment into buckets. * * @param array the array to be sorted * @param left the left boundary of the segment * @param right the right boundary of the segment * @param min the minimum element in the segment * @param max the maximum element in the segment * @param numBuckets the number of buckets * @param buckets the array of buckets * @param <T> the type of elements in the array */ private <T extends Comparable<T>> void distributeElements(final T[] array, final int left, final int right, final T min, final T max, final int numBuckets, final Bucket<T>[] buckets) { final double range = max.compareTo(min); for (int i = left; i <= right; i++) { final int scaleRangeDifference = array[i].compareTo(min) * numBuckets; int bucketIndex = (int) (scaleRangeDifference / (range + 1)); buckets[bucketIndex].add(array[i]); } } /** * Collects elements from the buckets back into the array. * * @param array the array to be sorted * @param left the left boundary of the segment * @param buckets the array of buckets * @param <T> the type of elements in the array */ private <T extends Comparable<T>> void collectElements(final T[] array, final int left, final Bucket<T>[] buckets) { int index = left; for (Bucket<T> bucket : buckets) { if (bucket.size() > 0) { T[] bucketArray = bucket.toArray(); spreadSort(bucketArray, 0, bucketArray.length - 1); for (T element : bucketArray) { array[index++] = element; } } } } /** * Insertion sort implementation for small segments. * * @param array the array to be sorted * @param left the left boundary of the segment * @param right the right boundary of the segment * @param <T> the type of elements in the array */ private <T extends Comparable<T>> void insertionSort(final T[] array, final int left, final int right) { for (int i = left + 1; i <= right; i++) { T key = array[i]; int j = i - 1; while (j >= left && SortUtils.greater(array[j], key)) { array[j + 1] = array[j]; j--; } array[j + 1] = key; } } /** * Bucket class to hold elements during sorting. * * @param <T> the type of elements in the bucket */ private static class Bucket<T extends Comparable<T>> { private T[] elements; private int size; /** * Constructs a new bucket with initial capacity. */ @SuppressWarnings("unchecked") Bucket(int initialBucketCapacity) { elements = (T[]) new Comparable[initialBucketCapacity]; size = 0; } /** * Adds an element to the bucket. * * @param element the element to add */ void add(T element) { if (size == elements.length) { elements = Arrays.copyOf(elements, size * 2); } elements[size++] = element; } /** * Returns the number of elements in the bucket. * * @return the size of the bucket */ int size() { return size; } /** * Returns an array containing all elements in the bucket. * * @return an array containing all elements in the bucket */ @SuppressWarnings("unchecked") T[] toArray() { return Arrays.copyOf(elements, size); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/WiggleSort.java
src/main/java/com/thealgorithms/sorts/WiggleSort.java
package com.thealgorithms.sorts; import static com.thealgorithms.maths.Ceil.ceil; import static com.thealgorithms.maths.Floor.floor; import static com.thealgorithms.searches.QuickSelect.select; import java.util.Arrays; /** * A wiggle sort implementation based on John L.s' answer in * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity * Also have a look at: * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable * arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2, * 2]. */ public class WiggleSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] unsorted) { return wiggleSort(unsorted); } private int mapIndex(int index, int n) { return ((2 * index + 1) % (n | 1)); } /** * Modified Dutch National Flag Sort. See also: sorts/DutchNationalFlagSort * * @param sortThis array to sort into group "greater", "equal" and "smaller" than median * @param median defines the groups * @param <T> extends interface Comparable */ private <T extends Comparable<T>> void triColorSort(T[] sortThis, T median) { int n = sortThis.length; int i = 0; int j = 0; int k = n - 1; while (j <= k) { if (0 < sortThis[mapIndex(j, n)].compareTo(median)) { SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(i, n)); i++; j++; } else if (0 > sortThis[mapIndex(j, n)].compareTo(median)) { SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(k, n)); k--; } else { j++; } } } private <T extends Comparable<T>> T[] wiggleSort(T[] sortThis) { // find the median using quickSelect (if the result isn't in the array, use the next greater // value) T median; median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0)); int numMedians = 0; for (T sortThi : sortThis) { if (0 == sortThi.compareTo(median)) { numMedians++; } } // added condition preventing off-by-one errors for odd arrays. // https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1 if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) { T smallestValue = select(Arrays.asList(sortThis), 0); if (!(0 == smallestValue.compareTo(median))) { throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, " + "the median has to be the smallest values in the array."); } } if (numMedians > ceil(sortThis.length / 2.0)) { throw new IllegalArgumentException("No more than half the number of values may be the same."); } triColorSort(sortThis, median); return sortThis; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
package com.thealgorithms.sorts; /** * Dual Pivot Quick Sort Algorithm * * @author Debasish Biswas (https://github.com/debasishbsws) * * @see SortAlgorithm */ public class DualPivotQuickSort implements SortAlgorithm { /** * Sorts an array using the Dual Pivot QuickSort algorithm. * * @param array The array to be sorted * @param <T> The type of elements in the array, which must be comparable * @return The sorted array */ @Override public <T extends Comparable<T>> T[] sort(final T[] array) { if (array.length <= 1) { return array; } dualPivotQuicksort(array, 0, array.length - 1); return array; } /** * Recursively applies the Dual Pivot QuickSort algorithm to subarrays. * * @param array The array to be sorted * @param left The starting index of the subarray * @param right The ending index of the subarray * @param <T> The type of elements in the array, which must be comparable */ private static <T extends Comparable<T>> void dualPivotQuicksort(final T[] array, final int left, final int right) { if (left < right) { final int[] pivots = partition(array, left, right); dualPivotQuicksort(array, left, pivots[0] - 1); dualPivotQuicksort(array, pivots[0] + 1, pivots[1] - 1); dualPivotQuicksort(array, pivots[1] + 1, right); } } /** * Partitions the array into three parts using two pivots. * * @param array The array to be partitioned * @param left The starting index for partitioning * @param right The ending index for partitioning * @param <T> The type of elements in the array, which must be comparable * @return An array containing the indices of the two pivots */ private static <T extends Comparable<T>> int[] partition(final T[] array, int left, final int right) { if (SortUtils.greater(array[left], array[right])) { SortUtils.swap(array, left, right); } final T pivot1 = array[left]; final T pivot2 = array[right]; int pivot1End = left + 1; int low = left + 1; int high = right - 1; while (low <= high) { if (SortUtils.less(array[low], pivot1)) { SortUtils.swap(array, low, pivot1End); pivot1End++; } else if (SortUtils.greaterOrEqual(array[low], pivot2)) { while (low < high && SortUtils.greater(array[high], pivot2)) { high--; } SortUtils.swap(array, low, high); high--; if (SortUtils.less(array[low], pivot1)) { SortUtils.swap(array, low, pivot1End); pivot1End++; } } low++; } // Place the pivots in their correct positions pivot1End--; high++; SortUtils.swap(array, left, pivot1End); SortUtils.swap(array, right, high); // Return the indices of the pivots return new int[] {low, high}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/ShellSort.java
src/main/java/com/thealgorithms/sorts/ShellSort.java
package com.thealgorithms.sorts; public class ShellSort implements SortAlgorithm { /** * Implements generic shell sort. * * @param array the array to be sorted. * @param <T> the type of elements in the array. * @return the sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } int gap = calculateInitialGap(array.length); while (gap > 0) { performGapInsertionSort(array, gap); gap = calculateNextGap(gap); } return array; } /** * Calculates the initial gap value using the Knuth sequence. * * @param length the length of the array. * @return the initial gap value. */ private int calculateInitialGap(final int length) { int gap = 1; while (gap < length / 3) { gap = 3 * gap + 1; } return gap; } /** * Calculates the next gap value. * * @param currentGap the current gap value. * @return the next gap value. */ private int calculateNextGap(final int currentGap) { return currentGap / 3; } /** * Performs an insertion sort for the specified gap value. * * @param array the array to be sorted. * @param gap the current gap value. * @param <T> the type of elements in the array. */ private <T extends Comparable<T>> void performGapInsertionSort(final T[] array, final int gap) { for (int i = gap; i < array.length; i++) { T temp = array[i]; int j; for (j = i; j >= gap && SortUtils.less(temp, array[j - gap]); j -= gap) { array[j] = array[j - gap]; } array[j] = temp; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/StoogeSort.java
src/main/java/com/thealgorithms/sorts/StoogeSort.java
package com.thealgorithms.sorts; /** * @author Amir Hassan (https://github.com/ahsNT) * @see SortAlgorithm */ public class StoogeSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } sort(array, 0, array.length); return array; } public <T extends Comparable<T>> T[] sort(final T[] array, final int start, final int end) { if (SortUtils.less(array[end - 1], array[start])) { final T temp = array[start]; array[start] = array[end - 1]; array[end - 1] = temp; } final int length = end - start; if (length > 2) { int third = length / 3; sort(array, start, end - third); sort(array, start + third, end); sort(array, start, end - third); } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/FlashSort.java
src/main/java/com/thealgorithms/sorts/FlashSort.java
package com.thealgorithms.sorts; /** * Implementation of Flash Sort algorithm that implements the SortAlgorithm interface. * * Sorts an array using the Flash Sort algorithm. * <p> * Flash Sort is a distribution sorting algorithm that partitions the data into * different classes based on a classification array. It performs the sorting by * first distributing the data elements into different buckets (or classes) and * then permuting these buckets into the sorted order. * <p> * The method works as follows: * <ol> * <li>Finds the minimum and maximum values in the array.</li> * <li>Initializes a classification array `L` to keep track of the number of elements in each class.</li> * <li>Computes a normalization constant `c1` to map elements into classes.</li> * <li>Classifies each element of the array into the corresponding bucket in the classification array.</li> * <li>Transforms the classification array to compute the starting indices of each bucket.</li> * <li>Permutes the elements of the array into sorted order based on the classification.</li> * <li>Uses insertion sort for the final arrangement to ensure complete sorting.</li> * </ol> */ public class FlashSort implements SortAlgorithm { private double classificationRatio = 0.45; public FlashSort() { } public FlashSort(double classificationRatio) { if (classificationRatio <= 0 || classificationRatio >= 1) { throw new IllegalArgumentException("Classification ratio must be between 0 and 1 (exclusive)."); } this.classificationRatio = classificationRatio; } public double getClassificationRatio() { return classificationRatio; } public void setClassificationRatio(double classificationRatio) { if (classificationRatio <= 0 || classificationRatio >= 1) { throw new IllegalArgumentException("Classification ratio must be between 0 and 1 (exclusive)."); } this.classificationRatio = classificationRatio; } /** * Sorts an array using the Flash Sort algorithm. * * @param array the array to be sorted. * @param <T> the type of elements to be sorted, must be comparable. * @return the sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { flashSort(array); return array; } /** * Sorts an array using the Flash Sort algorithm. * * @param arr the array to be sorted. * @param <T> the type of elements to be sorted, must be comparable. */ private <T extends Comparable<? super T>> void flashSort(T[] arr) { if (arr.length == 0) { return; } final T min = findMin(arr); final int maxIndex = findMaxIndex(arr); if (arr[maxIndex].compareTo(min) == 0) { return; // All elements are the same } final int m = (int) (classificationRatio * arr.length); final int[] classificationArray = new int[m]; final double c1 = (double) (m - 1) / arr[maxIndex].compareTo(min); classify(arr, classificationArray, c1, min); transform(classificationArray); permute(arr, classificationArray, c1, min, arr.length, m); insertionSort(arr); } /** * Finds the minimum value in the array. * * @param arr the array to find the minimum value in. * @param <T> the type of elements in the array, must be comparable. * @return the minimum value in the array. */ private <T extends Comparable<? super T>> T findMin(final T[] arr) { T min = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i].compareTo(min) < 0) { min = arr[i]; } } return min; } /** * Finds the index of the maximum value in the array. * * @param arr the array to find the maximum value index in. * @param <T> the type of elements in the array, must be comparable. * @return the index of the maximum value in the array. */ private <T extends Comparable<? super T>> int findMaxIndex(final T[] arr) { int maxIndex = 0; for (int i = 1; i < arr.length; i++) { if (arr[i].compareTo(arr[maxIndex]) > 0) { maxIndex = i; } } return maxIndex; } /** * Classifies elements of the array into the classification array classificationArray. * * @param arr the array to be classified. * @param classificationArray the classification array holding the count of elements in each class. * @param c1 the normalization constant used to map the elements to the classification array. * @param min the minimum value in the array. * @param <T> the type of elements in the array, must be comparable. */ private <T extends Comparable<? super T>> void classify(final T[] arr, final int[] classificationArray, final double c1, final T min) { for (int i = 0; i < arr.length; i++) { int k = (int) (c1 * arr[i].compareTo(min)); classificationArray[k]++; } } /** * Transforms the classification array classificationArray into the starting index array. * * @param classificationArray the classification array holding the count of elements in each class. */ private void transform(final int[] classificationArray) { for (int i = 1; i < classificationArray.length; i++) { classificationArray[i] += classificationArray[i - 1]; } } /** * Permutes the array into sorted order based on the classification array classificationArray. * * @param arr the array to be permuted. * @param classificationArray the classification array holding the count of elements in each class. * @param c1 the normalization constant used to map the elements to the classification array. * @param min the minimum value in the array. * @param n the length of the array. * @param m the number of classes in the classification array. * @param <T> the type of elements in the array, must be comparable. */ private <T extends Comparable<? super T>> void permute(final T[] arr, final int[] classificationArray, final double c1, T min, int n, int m) { int move = 0; int j = 0; int k = m - 1; T flash; while (move < n - 1) { while (j > classificationArray[k] - 1) { j++; k = (int) (c1 * arr[j].compareTo(min)); } flash = arr[j]; while (j != classificationArray[k]) { k = (int) (c1 * flash.compareTo(min)); T temp = arr[classificationArray[k] - 1]; arr[classificationArray[k] - 1] = flash; flash = temp; classificationArray[k]--; move++; } } } /** * Sorts an array using the insertion sort algorithm. * * @param arr the array to be sorted. * @param <T> the type of elements to be sorted, must be comparable. */ private <T extends Comparable<? super T>> void insertionSort(final T[] arr) { int n = arr.length; for (int i = 1; i < n; i++) { T key = arr[i]; int j = i - 1; while (j >= 0 && arr[j].compareTo(key) > 0) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BeadSort.java
src/main/java/com/thealgorithms/sorts/BeadSort.java
package com.thealgorithms.sorts; import java.util.Arrays; public class BeadSort { private enum BeadState { BEAD, EMPTY } /** * Sorts the given array using the BeadSort algorithm. * * @param array The array of non-negative integers to be sorted. * @return The sorted array. * @throws IllegalArgumentException If the array contains negative numbers. */ public int[] sort(int[] array) { allInputsMustBeNonNegative(array); return extractSortedFromGrid(fillGrid(array)); } private void allInputsMustBeNonNegative(final int[] array) { if (Arrays.stream(array).anyMatch(s -> s < 0)) { throw new IllegalArgumentException("BeadSort cannot sort negative numbers."); } } private BeadState[][] fillGrid(final int[] array) { final var maxValue = Arrays.stream(array).max().orElse(0); var grid = getEmptyGrid(array.length, maxValue); int[] count = new int[maxValue]; for (int i = 0, arrayLength = array.length; i < arrayLength; i++) { int k = 0; for (int j = 0; j < array[i]; j++) { grid[count[maxValue - k - 1]++][k] = BeadState.BEAD; k++; } } return grid; } private BeadState[][] getEmptyGrid(final int arrayLength, final int maxValue) { BeadState[][] grid = new BeadState[arrayLength][maxValue]; for (int i = 0; i < arrayLength; i++) { for (int j = 0; j < maxValue; j++) { grid[i][j] = BeadState.EMPTY; } } return grid; } private int[] extractSortedFromGrid(final BeadState[][] grid) { int[] sorted = new int[grid.length]; for (int i = 0; i < grid.length; i++) { int k = 0; for (int j = 0; j < grid[grid.length - 1 - i].length && grid[grid.length - 1 - i][j] == BeadState.BEAD; j++) { k++; } sorted[i] = k; } return sorted; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/PancakeSort.java
src/main/java/com/thealgorithms/sorts/PancakeSort.java
package com.thealgorithms.sorts; /** * Implementation of pancake sort * * @author Podshivalov Nikita (https://github.com/nikitap492) * @since 2018-04-10 */ public class PancakeSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length < 2) { return array; } for (int currentSize = 0; currentSize < array.length; currentSize++) { int maxIndex = findMaxIndex(array, currentSize); SortUtils.flip(array, maxIndex, array.length - 1 - currentSize); } return array; } /** * Finds the index of the maximum element in the array up to the given size. * * @param array the array to be searched * @param currentSize the current size of the unsorted portion of the array * @param <T> the type of elements in the array * @return the index of the maximum element */ private <T extends Comparable<T>> int findMaxIndex(T[] array, int currentSize) { T max = array[0]; int maxIndex = 0; for (int i = 0; i < array.length - currentSize; i++) { if (SortUtils.less(max, array[i])) { max = array[i]; maxIndex = i; } } return maxIndex; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/PatienceSort.java
src/main/java/com/thealgorithms/sorts/PatienceSort.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PriorityQueue; /** * This class implements the Patience Sort algorithm. Patience Sort is a sorting algorithm that * is particularly good for sorting sequences that are already partially sorted. */ public class PatienceSort implements SortAlgorithm { /** * Sorts an array of comparable elements using the Patience Sort algorithm. * * @param array the array to be sorted * @param <T> the type of elements in the array, must be comparable * @return the sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } final List<List<T>> piles = formPiles(array); final PriorityQueue<PileNode<T>> pq = mergePiles(piles); extractPiles(array, pq); return array; } /** * Forms piles from the given array. Each pile is a list of elements where * each element is smaller than the one before it. Binary search is used * to find the appropriate pile for each element. * * @param array the array of elements to be organized into piles * @param <T> the type of elements in the array, must be comparable * @return a list of piles */ private static <T extends Comparable<T>> List<List<T>> formPiles(final T[] array) { final List<List<T>> piles = new ArrayList<>(); final List<T> lastElements = new ArrayList<>(); for (T x : array) { int pos = Collections.binarySearch(lastElements, x); if (pos < 0) { pos = -pos - 1; } if (pos < piles.size()) { piles.get(pos).add(x); lastElements.set(pos, x); } else { List<T> newPile = new ArrayList<>(); newPile.add(x); piles.add(newPile); lastElements.add(x); } } return piles; } /** * Merges the piles into a priority queue where the smallest elements are * prioritized. * * @param piles the list of piles to be merged * @param <T> the type of elements in the piles, must be comparable * @return a priority queue containing the top element of each pile */ private static <T extends Comparable<T>> PriorityQueue<PileNode<T>> mergePiles(final Iterable<List<T>> piles) { PriorityQueue<PileNode<T>> pq = new PriorityQueue<>(); for (List<T> pile : piles) { pq.add(new PileNode<>(pile.removeLast(), pile)); } return pq; } /** * Extracts elements from the priority queue to form the sorted array. * * @param array the array to be filled with sorted elements * @param pq the priority queue containing the elements to be extracted * @param <T> the type of elements in the array, must be comparable */ private static <T extends Comparable<T>> void extractPiles(final T[] array, final PriorityQueue<PileNode<T>> pq) { int index = 0; while (!pq.isEmpty()) { PileNode<T> node = pq.poll(); array[index++] = node.value; if (!node.pile.isEmpty()) { pq.add(new PileNode<>(node.pile.removeLast(), node.pile)); } } } /** * A helper record representing a node in the priority queue. * * @param <T> the type of elements in the node, must be comparable */ private record PileNode<T extends Comparable<T>>(T value, List<T> pile) implements Comparable<PileNode<T>> { @Override public int compareTo(PileNode<T> other) { return this.value.compareTo(other.value); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/MergeSort.java
src/main/java/com/thealgorithms/sorts/MergeSort.java
package com.thealgorithms.sorts; import static com.thealgorithms.sorts.SortUtils.less; /** * Generic merge sort algorithm. * * @see SortAlgorithm */ @SuppressWarnings("rawtypes") class MergeSort implements SortAlgorithm { private Comparable[] aux; /** * Generic merge sort algorithm. * * Time Complexity: * - Best case: O(n log n) * - Average case: O(n log n) * - Worst case: O(n log n) * * Space Complexity: O(n) – requires auxiliary array for merging. * * @see SortAlgorithm */ @Override public <T extends Comparable<T>> T[] sort(T[] unsorted) { aux = new Comparable[unsorted.length]; doSort(unsorted, 0, unsorted.length - 1); return unsorted; } /** * @param arr the array to be sorted. * @param left the first index of the array. * @param right the last index of the array. */ private <T extends Comparable<T>> void doSort(T[] arr, int left, int right) { if (left < right) { int mid = (left + right) >>> 1; doSort(arr, left, mid); doSort(arr, mid + 1, right); merge(arr, left, mid, right); } } /** * Merges two parts of an array. * * @param arr the array to be merged. * @param left the first index of the array. * @param mid the middle index of the array. * @param right the last index of the array merges two parts of an array in * increasing order. */ @SuppressWarnings("unchecked") private <T extends Comparable<T>> void merge(T[] arr, int left, int mid, int right) { int i = left; int j = mid + 1; System.arraycopy(arr, left, aux, left, right + 1 - left); for (int k = left; k <= right; k++) { if (j > right) { arr[k] = (T) aux[i++]; } else if (i > mid) { arr[k] = (T) aux[j++]; } else if (less(aux[j], aux[i])) { arr[k] = (T) aux[j++]; } else { arr[k] = (T) aux[i++]; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/ExchangeSort.java
src/main/java/com/thealgorithms/sorts/ExchangeSort.java
package com.thealgorithms.sorts; /** * ExchangeSort is an implementation of the Exchange Sort algorithm. * * <p> * Exchange sort works by comparing each element with all subsequent elements, * swapping where needed, to ensure the correct placement of each element * in the final sorted order. It iteratively performs this process for each * element in the array. While it lacks the advantage of bubble sort in * detecting sorted lists in one pass, it can be more efficient than bubble sort * due to a constant factor (one less pass over the data to be sorted; half as * many total comparisons) in worst-case scenarios. * </p> * * <p> * Reference: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort * </p> * * @author 555vedant (Vedant Kasar) */ class ExchangeSort implements SortAlgorithm { /** * Implementation of Exchange Sort Algorithm * * @param array the array to be sorted. * @param <T> the type of elements in the array. * @return the sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { for (int i = 0; i < array.length - 1; i++) { for (int j = i + 1; j < array.length; j++) { if (SortUtils.greater(array[i], array[j])) { SortUtils.swap(array, i, j); } } } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/QuickSort.java
src/main/java/com/thealgorithms/sorts/QuickSort.java
package com.thealgorithms.sorts; /** * QuickSort is a divide-and-conquer sorting algorithm. * * <p>The algorithm selects a pivot element and partitions the array into two * subarrays such that: * <ul> * <li>Elements smaller than the pivot are placed on the left</li> * <li>Elements greater than the pivot are placed on the right</li> * </ul> * * <p>The subarrays are then recursively sorted until the entire array is ordered. * * <p>This implementation uses randomization to reduce the probability of * encountering worst-case performance on already sorted inputs. * * <p>Time Complexity: * <ul> * <li>Best Case: O(n log n)</li> * <li>Average Case: O(n log n)</li> * <li>Worst Case: O(n^2)</li> * </ul> * * <p>Space Complexity: O(log n) due to recursion stack (in-place sorting). * * @author Varun Upadhyay * @author Podshivalov Nikita * @see SortAlgorithm */ class QuickSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { doSort(array, 0, array.length - 1); return array; } /** * The sorting process * * @param array The array to be sorted * @param left The first index of an array * @param right The last index of an array */ private static <T extends Comparable<T>> void doSort(T[] array, final int left, final int right) { // Continue sorting only if the subarray has more than one element if (left < right) { // Randomly choose a pivot and partition the array final int pivot = randomPartition(array, left, right); // Recursively sort elements before the pivot doSort(array, left, pivot - 1); // Recursively sort elements after the pivot doSort(array, pivot, right); } } /** * Randomizes the array to avoid already ordered or nearly ordered sequences * * @param array The array to be sorted * @param left The first index of an array * @param right The last index of an array * @return the partition index of the array */ private static <T extends Comparable<T>> int randomPartition(T[] array, final int left, final int right) { // Randomizing the pivot helps avoid worst-case performance // for already sorted or nearly sorted arrays final int randomIndex = left + (int) (Math.random() * (right - left + 1)); SortUtils.swap(array, randomIndex, right); return partition(array, left, right); } /** * This method finds the partition index for an array * * @param array The array to be sorted * @param left The first index of an array * @param right The last index of an array */ private static <T extends Comparable<T>> int partition(T[] array, int left, int right) { final int mid = (left + right) >>> 1; // Choose the middle element as the pivot final T pivot = array[mid]; // Move the left and right pointers towards each other while (left <= right) { // Move left pointer until an element >= pivot is found while (SortUtils.less(array[left], pivot)) { ++left; } // Move right pointer until an element <= pivot is found while (SortUtils.less(pivot, array[right])) { --right; } // Swap elements that are on the wrong side of the pivot if (left <= right) { SortUtils.swap(array, left, right); ++left; --right; } } return left; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/RadixSort.java
src/main/java/com/thealgorithms/sorts/RadixSort.java
package com.thealgorithms.sorts; import com.thealgorithms.maths.NumberOfDigits; import java.util.Arrays; /** * This class provides an implementation of the radix sort algorithm. * It sorts an array of nonnegative integers in increasing order. */ public final class RadixSort { private static final int BASE = 10; private RadixSort() { } /** * Sorts an array of nonnegative integers using the radix sort algorithm. * * @param array the array to be sorted * @return the sorted array * @throws IllegalArgumentException if any negative integers are found */ public static int[] sort(int[] array) { if (array.length == 0) { return array; } checkForNegativeInput(array); radixSort(array); return array; } /** * Checks if the array contains any negative integers. * * @param array the array to be checked * @throws IllegalArgumentException if any negative integers are found */ private static void checkForNegativeInput(int[] array) { for (int number : array) { if (number < 0) { throw new IllegalArgumentException("Array contains non-positive integers."); } } } private static void radixSort(int[] array) { final int max = Arrays.stream(array).max().getAsInt(); for (int i = 0, exp = 1; i < NumberOfDigits.numberOfDigits(max); i++, exp *= BASE) { countingSortByDigit(array, exp); } } /** * A utility method to perform counting sort of array[] according to the digit represented by exp. * * @param array the array to be sorted * @param exp the exponent representing the current digit position */ private static void countingSortByDigit(int[] array, int exp) { int[] count = countDigits(array, exp); accumulateCounts(count); int[] output = buildOutput(array, exp, count); copyOutput(array, output); } private static int[] countDigits(int[] array, int exp) { int[] count = new int[BASE]; for (int i = 0; i < array.length; i++) { count[getDigit(array[i], exp)]++; } return count; } private static int getDigit(int number, int position) { return (number / position) % BASE; } private static void accumulateCounts(int[] count) { for (int i = 1; i < BASE; i++) { count[i] += count[i - 1]; } } private static int[] buildOutput(int[] array, int exp, int[] count) { int[] output = new int[array.length]; for (int i = array.length - 1; i >= 0; i--) { int digit = getDigit(array[i], exp); output[count[digit] - 1] = array[i]; count[digit]--; } return output; } private static void copyOutput(int[] array, int[] output) { System.arraycopy(output, 0, array, 0, array.length); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
package com.thealgorithms.sorts; import java.util.ArrayList; import java.util.List; public class MergeSortRecursive { List<Integer> arr; public MergeSortRecursive(List<Integer> arr) { this.arr = arr; } public List<Integer> mergeSort() { return merge(arr); } private static List<Integer> merge(List<Integer> arr) { // base condition if (arr.size() <= 1) { return arr; } int arrLength = arr.size(); int half = arrLength / 2; List<Integer> arrA = arr.subList(0, half); List<Integer> arrB = arr.subList(half, arr.size()); // recursion arrA = merge(arrA); arrB = merge(arrB); return sort(arrA, arrB); } private static List<Integer> sort(List<Integer> unsortedA, List<Integer> unsortedB) { if (unsortedA.isEmpty() && unsortedB.isEmpty()) { return new ArrayList<>(); } if (unsortedA.isEmpty()) { return unsortedB; } if (unsortedB.isEmpty()) { return unsortedA; } if (unsortedA.get(0) <= unsortedB.get(0)) { List<Integer> newAl = new ArrayList<Integer>() { { add(unsortedA.get(0)); } }; newAl.addAll(sort(unsortedA.subList(1, unsortedA.size()), unsortedB)); return newAl; } else { List<Integer> newAl = new ArrayList<Integer>() { { add(unsortedB.get(0)); } }; newAl.addAll(sort(unsortedA, unsortedB.subList(1, unsortedB.size()))); return newAl; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/CombSort.java
src/main/java/com/thealgorithms/sorts/CombSort.java
package com.thealgorithms.sorts; /** * Comb Sort algorithm implementation * * <p> * Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) * Worst-case space complexity O(1) * * <p> * Comb sort improves on bubble sort. * * @author Sandeep Roy (https://github.com/sandeeproy99) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BubbleSort * @see SortAlgorithm */ class CombSort implements SortAlgorithm { private static final double SHRINK_FACTOR = 1.3; /** * Method to find the next gap * * @param gap the current gap * @return the next gap value */ private int getNextGap(int gap) { gap = (int) (gap / SHRINK_FACTOR); return Math.max(gap, 1); } /** * Method to sort the array using CombSort * * @param arr the array to be sorted * @param <T> the type of elements in the array * @return the sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] arr) { int gap = arr.length; boolean swapped = true; while (gap != 1 || swapped) { gap = getNextGap(gap); swapped = performSwaps(arr, gap); } return arr; } /** * Method to perform the swapping of elements in the array based on the current gap * * @param arr the array to be sorted * @param gap the current gap * @param <T> the type of elements in the array * @return true if a swap occurred, false otherwise */ private <T extends Comparable<T>> boolean performSwaps(final T[] arr, final int gap) { boolean swapped = false; for (int i = 0; i < arr.length - gap; i++) { if (SortUtils.less(arr[i + gap], arr[i])) { SortUtils.swap(arr, i, i + gap); swapped = true; } } return swapped; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/LinkListSort.java
src/main/java/com/thealgorithms/sorts/LinkListSort.java
package com.thealgorithms.sorts; import java.util.Arrays; /** * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> * Program description - To sort the LinkList as per sorting technique */ public class LinkListSort { public static boolean isSorted(int[] p, int option) { int[] a = p; // Array is taken as input from test class int[] b = p; // array similar to a int ch = option; // Choice is choosed as any number from 1 to 3 (So the linked list will be // sorted by Merge sort technique/Insertion sort technique/Heap sort technique) switch (ch) { case 1: Task nm = new Task(); Node start = null; Node prev = null; Node fresh; Node ptr; for (int i = 0; i < a.length; i++) { // New nodes are created and values are added fresh = new Node(); // Node class is called fresh.val = a[i]; // Node val is stored if (start == null) { start = fresh; } else { prev.next = fresh; } prev = fresh; } start = nm.sortByMergeSort(start); // method is being called int i = 0; for (ptr = start; ptr != null; ptr = ptr.next) { a[i++] = ptr.val; // storing the sorted values in the array } Arrays.sort(b); // array b is sorted and it will return true when checked with sorted list LinkListSort uu = new LinkListSort(); return uu.compare(a, b); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed case 2: Node start1 = null; Node prev1 = null; Node fresh1; Node ptr1; for (int i1 = 0; i1 < a.length; i1++) { // New nodes are created and values are added fresh1 = new Node(); // New node is created fresh1.val = a[i1]; // Value is stored in the value part of the node if (start1 == null) { start1 = fresh1; } else { prev1.next = fresh1; } prev1 = fresh1; } Task1 kk = new Task1(); start1 = kk.sortByInsertionSort(start1); // method is being called int i1 = 0; for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { a[i1++] = ptr1.val; // storing the sorted values in the array } LinkListSort uu1 = new LinkListSort(); // array b is not sorted and it will return false when checked with sorted list return uu1.compare(a, b); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed case 3: Task2 mm = new Task2(); Node start2 = null; Node prev2 = null; Node fresh2; Node ptr2; for (int i2 = 0; i2 < a.length; i2++) { // New nodes are created and values are added fresh2 = new Node(); // Node class is created fresh2.val = a[i2]; // Value is stored in the value part of the Node if (start2 == null) { start2 = fresh2; } else { prev2.next = fresh2; } prev2 = fresh2; } start2 = mm.sortByHeapSort(start2); // method is being called int i3 = 0; for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { a[i3++] = ptr2.val; // storing the sorted values in the array } Arrays.sort(b); // array b is sorted and it will return true when checked with sorted list LinkListSort uu2 = new LinkListSort(); return uu2.compare(a, b); // The given array and the expected array is checked if both are same then true // is displayed else false is displayed default: // default is used in case user puts a unauthorized value System.out.println("Wrong choice"); } // Switch case is used to call the classes as per the user requirement return false; } /** * OUTPUT : * Input - {89,56,98,123,26,75,12,40,39,68,91} is same for all the 3 classes * Output: [12 26 39 40 56 68 75 89 91 98 123] is same for all the 3 classes * 1st approach Time Complexity : O(n logn) * Auxiliary Space Complexity : O(n) * 2nd approach Time Complexity : O(n^2) * Auxiliary Space Complexity : O(n) * 3rd approach Time Complexity : O(n logn) * Auxiliary Space Complexity : O(n) */ boolean compare(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; // Both the arrays are checked for equalness. If both are equal then true is // returned else false is returned } } class Node { int val; Node next; // Node class for creation of linklist nodes } class Task { private int[] a; public Node sortByMergeSort(Node head) { if (head == null || head.next == null) { return head; } int c = count(head); a = new int[c]; // Array of size c is created int i = 0; for (Node ptr = head; ptr != null; ptr = ptr.next) { a[i++] = ptr.val; } // values are stored in the array i = 0; task(a, 0, c - 1); // task method will be executed for (Node ptr = head; ptr != null; ptr = ptr.next) { ptr.val = a[i++]; // Value is stored in the linklist after being sorted } return head; } int count(Node head) { int c = 0; Node ptr; for (ptr = head; ptr != null; ptr = ptr.next) { c++; } return c; // This Method is used to count number of elements/nodes present in the linklist // It will return a integer type value denoting the number of nodes present } void task(int[] n, int i, int j) { if (i < j) { int m = (i + j) / 2; task(n, i, m); task(n, m + 1, j); task1(n, i, m, j); // Array is halved and sent for sorting } } void task1(int[] n, int s, int m, int e) { int i = s; int k = 0; int j = m + 1; int[] b = new int[e - s + 1]; while (i <= m && j <= e) { if (n[j] >= n[i]) { b[k++] = n[i++]; } else { b[k++] = n[j++]; } } // Smallest number is stored after checking from both the arrays while (i <= m) { b[k++] = n[i++]; } while (j <= e) { b[k++] = n[j++]; } for (int p = s; p <= e; p++) { a[p] = b[p - s]; } } // The method task and task1 is used to sort the linklist using merge sort } class Task1 { public Node sortByInsertionSort(Node head) { if (head == null || head.next == null) { return head; } int c = count(head); int[] a = new int[c]; // Array of size c is created a[0] = head.val; int i; Node ptr; for (ptr = head.next, i = 1; ptr != null; ptr = ptr.next, i++) { int j = i - 1; while (j >= 0 && a[j] > ptr.val) { // values are stored in the array a[j + 1] = a[j]; j--; } a[j + 1] = ptr.val; } i = 0; for (ptr = head; ptr != null; ptr = ptr.next) { ptr.val = a[i++]; // Value is stored in the linklist after being sorted } return head; } static int count(Node head) { Node ptr; int c = 0; for (ptr = head; ptr != null; ptr = ptr.next) { c++; } return c; // This Method is used to count number of elements/nodes present in the linklist // It will return a integer type value denoting the number of nodes present } // The method task and task1 is used to sort the linklist using insertion sort } class Task2 { public Node sortByHeapSort(Node head) { if (head == null || head.next == null) { return head; } int c = count(head); int[] a = new int[c]; // Array of size c is created int i = 0; for (Node ptr = head; ptr != null; ptr = ptr.next) { a[i++] = ptr.val; // values are stored in the array } i = 0; task(a); for (Node ptr = head; ptr != null; ptr = ptr.next) { ptr.val = a[i++]; // Value is stored in the linklist after being sorted } return head; } int count(Node head) { int c = 0; Node ptr; for (ptr = head; ptr != null; ptr = ptr.next) { c++; } return c; // This Method is used to count number of elements/nodes present in the linklist // It will return a integer type value denoting the number of nodes present } void task(int[] n) { int k = n.length; for (int i = k / 2 - 1; i >= 0; i--) { task1(n, k, i); } for (int i = k - 1; i > 0; i--) { int d = n[0]; n[0] = n[i]; n[i] = d; task1(n, i, 0); // recursive calling of task1 method } } void task1(int[] n, int k, int i) { int p = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < k && n[l] > n[p]) { p = l; } if (r < k && n[r] > n[p]) { p = r; } if (p != i) { int d = n[p]; n[p] = n[i]; n[i] = d; task1(n, k, p); } } // The method task and task1 is used to sort the linklist using heap sort }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java
src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java
package com.thealgorithms.sorts; /** * BubbleSort algorithm implemented using recursion */ public class BubbleSortRecursive implements SortAlgorithm { /** * @param array - an array should be sorted * @return sorted array */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { bubbleSort(array, array.length); return array; } /** * BubbleSort algorithm implements using recursion * * @param array array contains elements * @param len length of given array */ private static <T extends Comparable<T>> void bubbleSort(T[] array, int len) { boolean swapped = false; for (int i = 0; i < len - 1; ++i) { if (SortUtils.greater(array[i], array[i + 1])) { SortUtils.swap(array, i, i + 1); swapped = true; } } if (swapped) { bubbleSort(array, len - 1); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false