From 41efe7fbbc414fdf1cc06d7994f2edbf0d16a2ae Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Fri, 7 Jun 2024 19:59:53 +0200
Subject: [PATCH 001/607] style: include `DMC_DUBIOUS_MAP_COLLECTION` (#5207)
---
spotbugs-exclude.xml | 3 --
.../thealgorithms/maths/GenericRootTest.java | 30 ++++++++++---------
2 files changed, 16 insertions(+), 17 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index ffafa51e76ed..a01e489ba878 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -198,9 +198,6 @@
-
-
-
diff --git a/src/test/java/com/thealgorithms/maths/GenericRootTest.java b/src/test/java/com/thealgorithms/maths/GenericRootTest.java
index 50858cde1ef0..2578cfe82305 100644
--- a/src/test/java/com/thealgorithms/maths/GenericRootTest.java
+++ b/src/test/java/com/thealgorithms/maths/GenericRootTest.java
@@ -1,24 +1,26 @@
package com.thealgorithms.maths;
-import static java.util.Map.entry;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.util.Map;
-import org.junit.jupiter.api.Test;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
public class GenericRootTest {
- private final Map testCases = Map.ofEntries(entry(0, 0), entry(1, 1), entry(12345, 6), entry(123, 6), entry(15937, 7), entry(222222, 3), entry(99999, 9));
- @Test
- public void testGenericRoot() {
- for (final var tc : testCases.entrySet()) {
- assertEquals(tc.getValue(), GenericRoot.genericRoot(tc.getKey()));
- }
+ @ParameterizedTest
+ @MethodSource("tcStream")
+ public void testGenericRoot(final int input, final int expected) {
+ assertEquals(expected, GenericRoot.genericRoot(input));
}
- @Test
- public void testGenericRootWithNegativeInputs() {
- for (final var tc : testCases.entrySet()) {
- assertEquals(tc.getValue(), GenericRoot.genericRoot(-tc.getKey()));
- }
+ @ParameterizedTest
+ @MethodSource("tcStream")
+ public void testGenericRootWithNegativeInputs(final int input, final int expected) {
+ assertEquals(expected, GenericRoot.genericRoot(-input));
+ }
+
+ private static Stream tcStream() {
+ return Stream.of(Arguments.of(0, 0), Arguments.of(1, 1), Arguments.of(12345, 6), Arguments.of(123, 6), Arguments.of(15937, 7), Arguments.of(222222, 3), Arguments.of(99999, 9));
}
}
From be38886d4361a4d8414a16031da27c0e0e62fe41 Mon Sep 17 00:00:00 2001
From: StarDxxx <36352922+StarDxxx@users.noreply.github.com>
Date: Sat, 8 Jun 2024 15:36:42 +0800
Subject: [PATCH 002/607] style: enable `OperatorWrap` in checkstyle (#5212)
---
checkstyle.xml | 2 +-
src/main/java/com/thealgorithms/ciphers/AES.java | 8 ++++----
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index 5ada9361d03c..4078ffbbf537 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -139,7 +139,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java
index cd04395e1b72..5d614afbe584 100644
--- a/src/main/java/com/thealgorithms/ciphers/AES.java
+++ b/src/main/java/com/thealgorithms/ciphers/AES.java
@@ -2756,8 +2756,8 @@ public static void main(String[] args) {
in = input.nextLine();
BigInteger encryptionKey = new BigInteger(in, 16);
System.out.println(
- "The encrypted message is: \n" +
- encrypt(plaintext, encryptionKey).toString(16)
+ "The encrypted message is: \n"
+ + encrypt(plaintext, encryptionKey).toString(16)
);
}
case 'D', 'd' -> {
@@ -2772,8 +2772,8 @@ public static void main(String[] args) {
in = input.nextLine();
BigInteger decryptionKey = new BigInteger(in, 16);
System.out.println(
- "The deciphered message is:\n" +
- decrypt(ciphertext, decryptionKey).toString(16)
+ "The deciphered message is:\n"
+ + decrypt(ciphertext, decryptionKey).toString(16)
);
}
default -> System.out.println("** End **");
From a81fb32e6cdd739889e115761694d0c11bac7b29 Mon Sep 17 00:00:00 2001
From: StarDxxx <36352922+StarDxxx@users.noreply.github.com>
Date: Sat, 8 Jun 2024 19:37:20 +0800
Subject: [PATCH 003/607] style: enable `TypeName` (#5214)
* style: enable `TypeName` in checkstyle
* style: enable `TypeName` in checkstyle
* Update directory
* style: use proper formatting
---------
Co-authored-by: StarDxxx
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
DIRECTORY.md | 26 ++++++++++---------
checkstyle.xml | 2 +-
pmd-exclude.properties | 2 +-
.../graphs/{A_Star.java => AStar.java} | 4 +--
.../graphs/DIJSKSTRAS_ALGORITHM.java | 4 +--
...dlist.java => MergeKSortedLinkedlist.java} | 2 +-
.../datastructures/lists/README.md | 2 +-
...rixTranspose.java => MatrixTranspose.java} | 4 +--
.../{countSetBits.java => CountSetBits.java} | 4 +--
.../others/RotateMatrixBy90Degrees.java | 4 +--
...ava => SortOrderAgnosticBinarySearch.java} | 4 +--
...java => LongestNonRepeativeSubstring.java} | 4 +--
...{zigZagPattern.java => ZigZagPattern.java} | 4 +--
...mbStairsTest.java => ClimbStairsTest.java} | 2 +-
.../others/CountSetBitsTest.java | 17 ++++++++++++
.../others/countSetBitsTest.java | 17 ------------
...=> SortOrderAgnosticBinarySearchTest.java} | 6 ++---
... => LongestNonRepeativeSubstringTest.java} | 6 ++---
...atternTest.java => ZigZagPatternTest.java} | 6 ++---
19 files changed, 61 insertions(+), 59 deletions(-)
rename src/main/java/com/thealgorithms/datastructures/graphs/{A_Star.java => AStar.java} (99%)
rename src/main/java/com/thealgorithms/datastructures/lists/{Merge_K_SortedLinkedlist.java => MergeKSortedLinkedlist.java} (96%)
rename src/main/java/com/thealgorithms/misc/{matrixTranspose.java => MatrixTranspose.java} (96%)
rename src/main/java/com/thealgorithms/others/{countSetBits.java => CountSetBits.java} (95%)
rename src/main/java/com/thealgorithms/searches/{sortOrderAgnosticBinarySearch.java => SortOrderAgnosticBinarySearch.java} (90%)
rename src/main/java/com/thealgorithms/strings/{longestNonRepeativeSubstring.java => LongestNonRepeativeSubstring.java} (93%)
rename src/main/java/com/thealgorithms/strings/zigZagPattern/{zigZagPattern.java => ZigZagPattern.java} (95%)
rename src/test/java/com/thealgorithms/dynamicprogramming/{climbStairsTest.java => ClimbStairsTest.java} (95%)
create mode 100644 src/test/java/com/thealgorithms/others/CountSetBitsTest.java
delete mode 100644 src/test/java/com/thealgorithms/others/countSetBitsTest.java
rename src/test/java/com/thealgorithms/searches/{sortOrderAgnosticBinarySearchTest.java => SortOrderAgnosticBinarySearchTest.java} (75%)
rename src/test/java/com/thealgorithms/strings/{longestNonRepeativeSubstringTest.java => LongestNonRepeativeSubstringTest.java} (64%)
rename src/test/java/com/thealgorithms/strings/zigZagPattern/{zigZagPatternTest.java => ZigZagPatternTest.java} (67%)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index c8b38bb20343..7c46336f0911 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -18,6 +18,7 @@
* [ParenthesesGenerator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java)
* [Permutation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Permutation.java)
* [PowerSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/PowerSum.java)
+ * [SubsequenceFinder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java)
* [WordSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/WordSearch.java)
* bitmanipulation
* [BitSwap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java)
@@ -96,7 +97,7 @@
* dynamicarray
* [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java)
* graphs
- * [A Star](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java)
+ * [AStar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java)
* [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java)
* [BipartiteGrapfDFS](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java)
* [BoruvkaAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java)
@@ -141,7 +142,7 @@
* [CreateAndDetectLoop](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java)
* [CursorLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java)
* [DoublyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java)
- * [Merge K SortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java)
+ * [MergeKSortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedlist.java)
* [MergeSortedArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java)
* [MergeSortedSinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java)
* [QuickSortLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/QuickSortLinkedList.java)
@@ -376,7 +377,7 @@
* [ColorContrastRatio](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java)
* [InverseOfMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java)
* [MapReduce](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MapReduce.java)
- * [matrixTranspose](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/matrixTranspose.java)
+ * [MatrixTranspose](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MatrixTranspose.java)
* [MedianOfMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfMatrix.java)
* [MedianOfRunningArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java)
* [MedianOfRunningArrayByte](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayByte.java)
@@ -403,7 +404,7 @@
* [HammingDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/cn/HammingDistance.java)
* [Conway](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Conway.java)
* [CountChar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountChar.java)
- * [countSetBits](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/countSetBits.java)
+ * [CountSetBits](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountSetBits.java)
* [CountWords](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountWords.java)
* [CRC16](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CRC16.java)
* [CRC32](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CRC32.java)
@@ -478,7 +479,7 @@
* [RowColumnWiseSorted2dArrayBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java)
* [SaddlebackSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java)
* [SearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java)
- * [sortOrderAgnosticBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java)
+ * [SortOrderAgnosticBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java)
* [SquareRootBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java)
* [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/TernarySearch.java)
* [UnionFind](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/UnionFind.java)
@@ -549,7 +550,7 @@
* [HorspoolSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/HorspoolSearch.java)
* [Isomorphic](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Isomorphic.java)
* [LetterCombinationsOfPhoneNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java)
- * [longestNonRepeativeSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java)
+ * [LongestNonRepeativeSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java)
* [LongestPalindromicSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java)
* [Lower](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Lower.java)
* [MyAtoi](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/MyAtoi.java)
@@ -565,7 +566,7 @@
* [ValidParentheses](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ValidParentheses.java)
* [WordLadder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/WordLadder.java)
* zigZagPattern
- * [zigZagPattern](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java)
+ * [ZigZagPattern](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java)
* test
* java
* com
@@ -580,6 +581,7 @@
* [ParenthesesGeneratorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java)
* [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java)
* [PowerSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java)
+ * [SubsequenceFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java)
* [WordSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java)
* bitmanipulation
* [BitSwapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java)
@@ -684,7 +686,7 @@
* [StrassenMatrixMultiplicationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java)
* dynamicprogramming
* [CatalanNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java)
- * [climbStairsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java)
+ * [ClimbStairsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java)
* [EggDroppingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java)
* [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java)
* [KnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java)
@@ -812,7 +814,7 @@
* [ConwayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ConwayTest.java)
* [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java)
* [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
- * [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java)
+ * [CountSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountSetBitsTest.java)
* [CountWordsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountWordsTest.java)
* [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java)
* [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java)
@@ -848,7 +850,7 @@
* [RabinKarpAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java)
* [RecursiveBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RecursiveBinarySearchTest.java)
* [RowColumnWiseSorted2dArrayBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java)
- * [sortOrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java)
+ * [SortOrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java)
* [TestSearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java)
* sorts
* [BeadSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BeadSortTest.java)
@@ -896,7 +898,7 @@
* [HorspoolSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java)
* [IsomorphicTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/IsomorphicTest.java)
* [LetterCombinationsOfPhoneNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java)
- * [longestNonRepeativeSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java)
+ * [LongestNonRepeativeSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java)
* [LowerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LowerTest.java)
* [MyAtoiTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/MyAtoiTest.java)
* [PalindromeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PalindromeTest.java)
@@ -910,4 +912,4 @@
* [ValidParenthesesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java)
* [WordLadderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/WordLadderTest.java)
* zigZagPattern
- * [zigZagPatternTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java)
+ * [ZigZagPatternTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java)
diff --git a/checkstyle.xml b/checkstyle.xml
index 4078ffbbf537..cb4ee54670ac 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -116,7 +116,7 @@
-
+
diff --git a/pmd-exclude.properties b/pmd-exclude.properties
index 400863992ed0..eb199da3a0d3 100644
--- a/pmd-exclude.properties
+++ b/pmd-exclude.properties
@@ -10,7 +10,7 @@ com.thealgorithms.conversions.HexToOct=UselessParentheses
com.thealgorithms.conversions.IntegerToRoman=UnnecessaryFullyQualifiedName
com.thealgorithms.datastructures.crdt.LWWElementSet=UselessParentheses
com.thealgorithms.datastructures.crdt.Pair=UnusedPrivateField
-com.thealgorithms.datastructures.graphs.A_Star=UselessParentheses
+com.thealgorithms.datastructures.graphs.AStar=UselessParentheses
com.thealgorithms.datastructures.graphs.AdjacencyMatrixGraph=CollapsibleIfStatements,UnnecessaryFullyQualifiedName,UselessParentheses
com.thealgorithms.datastructures.graphs.BipartiteGrapfDFS=CollapsibleIfStatements
com.thealgorithms.datastructures.graphs.Kruskal=UselessParentheses
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java
similarity index 99%
rename from src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
rename to src/main/java/com/thealgorithms/datastructures/graphs/AStar.java
index b1af21eb6ff2..54fb5fba5c1b 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java
@@ -9,8 +9,8 @@
import java.util.List;
import java.util.PriorityQueue;
-public final class A_Star {
- private A_Star() {
+public final class AStar {
+ private AStar() {
}
private static class Graph {
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
index 8503aa48ec37..419da4a9be73 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
@@ -4,7 +4,7 @@
*/
package com.thealgorithms.datastructures.graphs;
-class dijkstras {
+class Dijkstras {
int k = 9;
@@ -67,7 +67,7 @@ public static void main(String[] args) {
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
};
- dijkstras t = new dijkstras();
+ Dijkstras t = new Dijkstras();
t.dijkstra(graph, 0);
} // main
} // djikstras
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedlist.java
similarity index 96%
rename from src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java
rename to src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedlist.java
index a714eda18bcd..ece178908e63 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedlist.java
@@ -7,7 +7,7 @@
/**
* @author Arun Pandey (https://github.com/pandeyarun709)
*/
-public class Merge_K_SortedLinkedlist {
+public class MergeKSortedLinkedlist {
/**
* This function merge K sorted LinkedList
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/README.md b/src/main/java/com/thealgorithms/datastructures/lists/README.md
index cfb8221abca6..ea389c0422ce 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/README.md
+++ b/src/main/java/com/thealgorithms/datastructures/lists/README.md
@@ -27,6 +27,6 @@ The `next` variable points to the next node in the data structure and value stor
3. `CountSinglyLinkedListRecursion.java`: Recursively counts the size of a list.
4. `CreateAndDetectLoop.java` : Create and detect a loop in a linked list.
5. `DoublyLinkedList.java` : A modification of singly linked list which has a `prev` pointer to point to the previous node.
-6. `Merge_K_SortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list).
+6. `MergeKSortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list).
7. `RandomNode.java` : Selects a random node from given linked list and diplays it.
8. `SkipList.java` : Data Structure used for storing a sorted list of elements with help of a Linked list hierarchy that connects to subsequences of elements.
diff --git a/src/main/java/com/thealgorithms/misc/matrixTranspose.java b/src/main/java/com/thealgorithms/misc/MatrixTranspose.java
similarity index 96%
rename from src/main/java/com/thealgorithms/misc/matrixTranspose.java
rename to src/main/java/com/thealgorithms/misc/MatrixTranspose.java
index 40634f18b5f6..153cf4e9df99 100644
--- a/src/main/java/com/thealgorithms/misc/matrixTranspose.java
+++ b/src/main/java/com/thealgorithms/misc/MatrixTranspose.java
@@ -18,8 +18,8 @@
* @version 11.0.9
* @since 2014-03-31
*/
-public final class matrixTranspose {
- private matrixTranspose() {
+public final class MatrixTranspose {
+ private MatrixTranspose() {
}
public static void main(String[] args) {
diff --git a/src/main/java/com/thealgorithms/others/countSetBits.java b/src/main/java/com/thealgorithms/others/CountSetBits.java
similarity index 95%
rename from src/main/java/com/thealgorithms/others/countSetBits.java
rename to src/main/java/com/thealgorithms/others/CountSetBits.java
index 04e0d6f62e6e..b26f745d4cd7 100644
--- a/src/main/java/com/thealgorithms/others/countSetBits.java
+++ b/src/main/java/com/thealgorithms/others/CountSetBits.java
@@ -1,6 +1,6 @@
package com.thealgorithms.others;
-public class countSetBits {
+public class CountSetBits {
/**
* The below algorithm is called as Brian Kernighan's algorithm
@@ -40,7 +40,7 @@ public class countSetBits {
* @param num takes Long number whose number of set bit is to be found
* @return the count of set bits in the binary equivalent
*/
- public long countsetBits(long num) {
+ public long countSetBits(long num) {
long cnt = 0;
while (num > 0) {
cnt++;
diff --git a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
index 2ea3de814d0d..3930ca3e95ff 100644
--- a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
+++ b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
@@ -6,8 +6,8 @@
*/
import java.util.Scanner;
-final class Rotate_by_90_degrees {
- private Rotate_by_90_degrees() {
+final class RotateMatrixBy90Degrees {
+ private RotateMatrixBy90Degrees() {
}
public static void main(String[] args) {
diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java
similarity index 90%
rename from src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java
rename to src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java
index acb9fb5cb3cd..6a2a46c2821f 100644
--- a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java
@@ -1,6 +1,6 @@
package com.thealgorithms.searches;
-public final class sortOrderAgnosticBinarySearch {
- private sortOrderAgnosticBinarySearch() {
+public final class SortOrderAgnosticBinarySearch {
+ private SortOrderAgnosticBinarySearch() {
}
public static int find(int[] arr, int key) {
int start = 0;
diff --git a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
similarity index 93%
rename from src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java
rename to src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
index 99154542955f..140e668fc841 100644
--- a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java
+++ b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
@@ -2,8 +2,8 @@
import java.util.HashMap;
-final class longestNonRepeativeSubstring {
- private longestNonRepeativeSubstring() {
+final class LongestNonRepeativeSubstring {
+ private LongestNonRepeativeSubstring() {
}
public static int lengthOfLongestSubstring(String s) {
diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
similarity index 95%
rename from src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
rename to src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
index 2dfcf3909b8f..3337f6eeff71 100644
--- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
+++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
@@ -1,7 +1,7 @@
package com.thealgorithms.strings.zigZagPattern;
-final class zigZagPattern {
- private zigZagPattern() {
+final class ZigZagPattern {
+ private ZigZagPattern() {
}
public static String encode(String s, int numRows) {
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java
similarity index 95%
rename from src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java
rename to src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java
index 7df3127eec82..1f2de4a11b62 100644
--- a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java
@@ -4,7 +4,7 @@
import org.junit.jupiter.api.Test;
-public class climbStairsTest {
+public class ClimbStairsTest {
@Test
void climbStairsTestForTwo() {
diff --git a/src/test/java/com/thealgorithms/others/CountSetBitsTest.java b/src/test/java/com/thealgorithms/others/CountSetBitsTest.java
new file mode 100644
index 000000000000..ab34c6ba7876
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/CountSetBitsTest.java
@@ -0,0 +1,17 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class CountSetBitsTest {
+
+ @Test
+ void testSetBits() {
+ CountSetBits csb = new CountSetBits();
+ assertEquals(1L, csb.countSetBits(16));
+ assertEquals(4, csb.countSetBits(15));
+ assertEquals(5, csb.countSetBits(10000));
+ assertEquals(5, csb.countSetBits(31));
+ }
+}
diff --git a/src/test/java/com/thealgorithms/others/countSetBitsTest.java b/src/test/java/com/thealgorithms/others/countSetBitsTest.java
deleted file mode 100644
index 1429aac8daff..000000000000
--- a/src/test/java/com/thealgorithms/others/countSetBitsTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.thealgorithms.others;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
-
-public class countSetBitsTest {
-
- @Test
- void testSetBits() {
- countSetBits csb = new countSetBits();
- assertEquals(1L, csb.countsetBits(16));
- assertEquals(4, csb.countsetBits(15));
- assertEquals(5, csb.countsetBits(10000));
- assertEquals(5, csb.countsetBits(31));
- }
-}
diff --git a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java
similarity index 75%
rename from src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java
rename to src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java
index 04ed00ae85b9..e2917733d1d9 100644
--- a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java
+++ b/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java
@@ -4,13 +4,13 @@
import org.junit.jupiter.api.Test;
-public class sortOrderAgnosticBinarySearchTest {
+public class SortOrderAgnosticBinarySearchTest {
@Test
public void testAscending() {
int[] arr = {1, 2, 3, 4, 5}; // for ascending order.
int target = 2;
- int ans = sortOrderAgnosticBinarySearch.find(arr, target);
+ int ans = SortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 1;
assertEquals(excepted, ans);
}
@@ -19,7 +19,7 @@ public void testAscending() {
public void testDescending() {
int[] arr = {5, 4, 3, 2, 1}; // for descending order.
int target = 2;
- int ans = sortOrderAgnosticBinarySearch.find(arr, target);
+ int ans = SortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 3;
assertEquals(excepted, ans);
}
diff --git a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java b/src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java
similarity index 64%
rename from src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java
rename to src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java
index 2dce8cf38c05..4bd5ac996719 100644
--- a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java
+++ b/src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java
@@ -3,13 +3,13 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class longestNonRepeativeSubstringTest {
+public class LongestNonRepeativeSubstringTest {
@Test
public void palindrome() {
String input1 = "HelloWorld";
String input2 = "javaIsAProgrammingLanguage";
- Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5);
- Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9);
+ Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5);
+ Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9);
}
}
diff --git a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java b/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java
similarity index 67%
rename from src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java
rename to src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java
index 02904ddcf6c3..518bfab80f08 100644
--- a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java
+++ b/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java
@@ -3,13 +3,13 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class zigZagPatternTest {
+public class ZigZagPatternTest {
@Test
public void palindrome() {
String input1 = "HelloWorldFromJava";
String input2 = "javaIsAProgrammingLanguage";
- Assertions.assertEquals(zigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
- Assertions.assertEquals(zigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
+ Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
+ Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
}
}
From 0e8fed0dd63cbee83c6b3e6c7834ae64c3a27d42 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Tue, 11 Jun 2024 00:02:21 +0200
Subject: [PATCH 004/607] Chore(deps): bump gitpod/workspace-java-21 from
2024-06-03-17-43-12 to 2024-06-10-10-39-01 (#5218)
Chore(deps): bump gitpod/workspace-java-21
Bumps gitpod/workspace-java-21 from 2024-06-03-17-43-12 to 2024-06-10-10-39-01.
---
updated-dependencies:
- dependency-name: gitpod/workspace-java-21
dependency-type: direct:production
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.gitpod.dockerfile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile
index 82696623f953..6ca2b97e8442 100644
--- a/.gitpod.dockerfile
+++ b/.gitpod.dockerfile
@@ -1,4 +1,4 @@
-FROM gitpod/workspace-java-21:2024-06-03-17-43-12
+FROM gitpod/workspace-java-21:2024-06-10-10-39-01
ENV LLVM_SCRIPT="tmp_llvm.sh"
From 3ecd13508a8ebe533afe3486bac66cb3ab54cecb Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Wed, 12 Jun 2024 06:15:51 +0000
Subject: [PATCH 005/607] Chore(deps): bump
org.apache.maven.plugins:maven-pmd-plugin from 3.22.0 to 3.23.0 (#5220)
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin
Bumps [org.apache.maven.plugins:maven-pmd-plugin](https://github.com/apache/maven-pmd-plugin) from 3.22.0 to 3.23.0.
- [Release notes](https://github.com/apache/maven-pmd-plugin/releases)
- [Commits](https://github.com/apache/maven-pmd-plugin/compare/maven-pmd-plugin-3.22.0...maven-pmd-plugin-3.23.0)
---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-pmd-plugin
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index 6e8c9acf92b0..98771e184caa 100644
--- a/pom.xml
+++ b/pom.xml
@@ -146,7 +146,7 @@
org.apache.maven.pluginsmaven-pmd-plugin
- 3.22.0
+ 3.23.0truetrue
From f8698674b3785e046cb30ec9aec68fbab7eec195 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Thu, 13 Jun 2024 06:37:14 +0200
Subject: [PATCH 006/607] style: include `IM_BAD_CHECK_FOR_ODD` (#5213)
---
spotbugs-exclude.xml | 3 ---
src/main/java/com/thealgorithms/maths/SimpsonIntegration.java | 2 +-
2 files changed, 1 insertion(+), 4 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index a01e489ba878..8d80528696c0 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -65,9 +65,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
index 79bc112902c4..1163208a1f83 100644
--- a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
+++ b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
@@ -63,7 +63,7 @@ public double simpsonsMethod(int n, double h, double a) {
if (i == 0 || i == data.size() - 1) {
integralEvaluation += data.get(i);
System.out.println("Multiply f(x" + i + ") by 1");
- } else if (i % 2 == 1) {
+ } else if (i % 2 != 0) {
integralEvaluation += (double) 4 * data.get(i);
System.out.println("Multiply f(x" + i + ") by 4");
} else {
From a2af09cdfb9606c4818bbf98d188de77a6834dcc Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Thu, 13 Jun 2024 19:25:43 +0200
Subject: [PATCH 007/607] style: enable `ParenPad` in checkstyle (#5226)
* enable ParenPad
* style: enable ParenPad in checkstyle
---------
Co-authored-by: Samuel Facchinello
---
checkstyle.xml | 2 +-
.../thealgorithms/datastructures/graphs/BellmanFord.java | 8 +++++---
2 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index cb4ee54670ac..b65291b8ffa8 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -140,7 +140,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
index 522e19787e8c..47c5f0d0b98e 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
@@ -57,9 +57,11 @@ public static void main(String[] args) {
obj.go();
}
- public void go() { // shows distance to all vertices // Interactive run for understanding the
- try ( // class first time. Assumes source vertex is 0 and
- Scanner sc = new Scanner(System.in)) {
+ public void go() {
+ // shows distance to all vertices
+ // Interactive run for understanding the
+ // class first time. Assumes source vertex is 0 and
+ try (Scanner sc = new Scanner(System.in)) {
int i;
int v;
int e;
From 31db1af345b0635633d962a944210edaff3d5251 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Thu, 13 Jun 2024 19:27:49 +0200
Subject: [PATCH 008/607] style: include `SUI_CONTAINS_BEFORE_ADD` (#5216)
---
spotbugs-exclude.xml | 3 ---
.../datastructures/graphs/ConnectedComponent.java | 3 +--
2 files changed, 1 insertion(+), 5 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 8d80528696c0..0a5354382a4f 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -222,9 +222,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
index d2b76e8e06b1..520a1681774a 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
@@ -81,8 +81,7 @@ public int countGraphs() {
Set markedNodes = new HashSet();
for (Node n : nodeList) {
- if (!markedNodes.contains(n)) {
- markedNodes.add(n);
+ if (markedNodes.add(n)) {
markedNodes.addAll(depthFirstSearch(n, new ArrayList()));
count++;
}
From 51fcc6634505ddc36576b6e752897778faa8fcc9 Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Thu, 13 Jun 2024 19:40:12 +0200
Subject: [PATCH 009/607] refactor: redesign `LetterCombinationsOfPhoneNumber`
(#5221)
* Refactor
* fix clang
* fix clang
* fix clang tests
* fix pattern
* add test case null
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* rename MAP_OF_CHARS to KEYPAD
* fix clang
* remove main
* add tests
* feat: throw for wrong inputs
* change keypad to list
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* fix with number 1 (empty value), and add tests
* style: avoid concatenation while populating `KEYPAD`
* change to assertEquals
---------
Co-authored-by: Samuel Facchinello
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.../LetterCombinationsOfPhoneNumber.java | 80 +++++++++++--------
.../LetterCombinationsOfPhoneNumberTest.java | 58 ++++++--------
2 files changed, 71 insertions(+), 67 deletions(-)
diff --git a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
index 2e3ee25fb6ea..38c6bc13fa2a 100644
--- a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
+++ b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
@@ -5,49 +5,61 @@
import java.util.List;
public final class LetterCombinationsOfPhoneNumber {
+
+ private static final char EMPTY = '\0';
+
+ // Mapping of numbers to corresponding letters on a phone keypad
+ private static final String[] KEYPAD = new String[] {" ", String.valueOf(EMPTY), "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
+
private LetterCombinationsOfPhoneNumber() {
}
- static Character[][] numberToCharMap;
-
- protected static List printWords(int[] numbers, int len, int numIndex, String s) {
- if (len == numIndex) {
- return new ArrayList<>(Collections.singleton(s));
+ /**
+ * Generates a list of all possible letter combinations that the provided
+ * array of numbers could represent on a phone keypad.
+ *
+ * @param numbers an array of integers representing the phone numbers
+ * @return a list of possible letter combinations
+ */
+ public static List getCombinations(int[] numbers) {
+ if (numbers == null) {
+ return List.of("");
}
+ return generateCombinations(numbers, 0, new StringBuilder());
+ }
- List stringList = new ArrayList<>();
+ /**
+ * Recursive method to generate combinations of letters from the phone keypad.
+ *
+ * @param numbers the input array of phone numbers
+ * @param index the current index in the numbers array being processed
+ * @param current a StringBuilder holding the current combination of letters
+ * @return a list of letter combinations formed from the given numbers
+ */
+ private static List generateCombinations(int[] numbers, int index, StringBuilder current) {
+ // Base case: if we've processed all numbers, return the current combination
+ if (index == numbers.length) {
+ return new ArrayList<>(Collections.singletonList(current.toString()));
+ }
- for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) {
- String sCopy = String.copyValueOf(s.toCharArray());
- sCopy = sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString());
- stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy));
+ final var number = numbers[index];
+ if (number < 0 || number > 9) {
+ throw new IllegalArgumentException("Input numbers must in the range [0, 9]");
}
- return stringList;
- }
- private static void printWords(int[] numbers) {
- generateNumberToCharMap();
- List stringList = printWords(numbers, numbers.length, 0, "");
- stringList.stream().forEach(System.out::println);
- }
+ List combinations = new ArrayList<>();
- protected static void generateNumberToCharMap() {
- numberToCharMap = new Character[10][5];
- numberToCharMap[0] = new Character[] {'\0'};
- numberToCharMap[1] = new Character[] {'\0'};
- numberToCharMap[2] = new Character[] {'a', 'b', 'c'};
- numberToCharMap[3] = new Character[] {'d', 'e', 'f'};
- numberToCharMap[4] = new Character[] {'g', 'h', 'i'};
- numberToCharMap[5] = new Character[] {'j', 'k', 'l'};
- numberToCharMap[6] = new Character[] {'m', 'n', 'o'};
- numberToCharMap[7] = new Character[] {'p', 'q', 'r', 's'};
- numberToCharMap[8] = new Character[] {'t', 'u', 'v'};
- numberToCharMap[9] = new Character[] {'w', 'x', 'y', 'z'};
- }
+ // Iterate over each letter and recurse to generate further combinations
+ for (char letter : KEYPAD[number].toCharArray()) {
+ if (letter != EMPTY) {
+ current.append(letter);
+ }
+ combinations.addAll(generateCombinations(numbers, index + 1, current));
+ if (letter != EMPTY) {
+ current.deleteCharAt(current.length() - 1); // Backtrack by removing the last appended letter
+ }
+ }
- // Driver code
- public static void main(String[] args) {
- int[] number = {2, 3, 4};
- printWords(number);
+ return combinations;
}
}
diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
index 4ffbddcb44a8..dcdb7d5b3392 100644
--- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
+++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java
@@ -1,45 +1,37 @@
package com.thealgorithms.strings;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-import java.util.Arrays;
import java.util.List;
-import org.junit.jupiter.api.Test;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
public class LetterCombinationsOfPhoneNumberTest {
- @Test
- public void letterCombinationsOfPhoneNumber() {
- LetterCombinationsOfPhoneNumber.generateNumberToCharMap();
-
- // ** Test 1 **
- // Input: digits = ""
- // Output: []
- int[] numbers1 = {};
- List output1 = Arrays.asList("");
- assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers1, numbers1.length, 0, "").equals(output1));
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ public void testLetterCombinationsOfPhoneNumber(int[] numbers, List expectedOutput) {
+ assertEquals(expectedOutput, LetterCombinationsOfPhoneNumber.getCombinations(numbers));
+ }
- // ** Test 2 **
- // Input: digits = "2"
- // Output: ["a","b","c"]
- int[] numbers2 = {2};
- List output2 = Arrays.asList("a", "b", "c");
- assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers2, numbers2.length, 0, "").equals(output2));
+ @ParameterizedTest
+ @MethodSource("wrongInputs")
+ void throwsForWrongInput(int[] numbers) {
+ assertThrows(IllegalArgumentException.class, () -> LetterCombinationsOfPhoneNumber.getCombinations(numbers));
+ }
- // ** Test 3 **
- // Input: digits = "23"
- // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
- int[] numbers3 = {2, 3};
- List output3 = Arrays.asList("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf");
- assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers3, numbers3.length, 0, "").equals(output3));
+ private static Stream provideTestCases() {
+ return Stream.of(Arguments.of(null, List.of("")), Arguments.of(new int[] {}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")), Arguments.of(new int[] {2, 3}, List.of("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf")),
+ Arguments.of(new int[] {2, 3, 4}, List.of("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi")),
+ Arguments.of(new int[] {3, 3}, List.of("dd", "de", "df", "ed", "ee", "ef", "fd", "fe", "ff")), Arguments.of(new int[] {8, 4}, List.of("tg", "th", "ti", "ug", "uh", "ui", "vg", "vh", "vi")), Arguments.of(new int[] {2, 0}, List.of("a ", "b ", "c ")),
+ Arguments.of(new int[] {9, 2}, List.of("wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc")), Arguments.of(new int[] {0}, List.of(" ")), Arguments.of(new int[] {1}, List.of("")), Arguments.of(new int[] {2}, List.of("a", "b", "c")),
+ Arguments.of(new int[] {1, 2, 0, 4}, List.of("a g", "a h", "a i", "b g", "b h", "b i", "c g", "c h", "c i")));
+ }
- // ** Test 4 **
- // Input: digits = "234"
- // Output: ["adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi",
- // "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh",
- // "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"]
- int[] numbers4 = {2, 3, 4};
- List output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi");
- assertTrue(LetterCombinationsOfPhoneNumber.printWords(numbers4, numbers4.length, 0, "").equals(output4));
+ private static Stream wrongInputs() {
+ return Stream.of(Arguments.of(new int[] {-1}), Arguments.of(new int[] {10}), Arguments.of(new int[] {2, 2, -1, 0}), Arguments.of(new int[] {0, 0, 0, 10}));
}
}
From 87b17e05714d011fee82b35f11833bf12ec175cb Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Thu, 13 Jun 2024 21:00:16 +0200
Subject: [PATCH 010/607] style: enable `NeedBraces` in checkstyle (#5227)
* enable style NeedBraces
* style: enable NeedBraces in checkstyle
---------
Co-authored-by: Samuel Facchinello
---
checkstyle.xml | 2 +-
.../backtracking/Combination.java | 4 +-
.../thealgorithms/backtracking/MColoring.java | 4 +-
.../backtracking/WordSearch.java | 8 +-
.../com/thealgorithms/ciphers/Blowfish.java | 16 ++-
.../ciphers/a5/A5KeyStreamGenerator.java | 4 +-
.../ciphers/a5/CompositeLFSR.java | 4 +-
.../buffers/CircularBuffer.java | 12 +-
.../datastructures/graphs/Kosaraju.java | 8 +-
.../graphs/TarjansAlgorithm.java | 4 +-
.../hashmap/hashing/HashMap.java | 8 +-
.../hashmap/hashing/HashMapCuckooHashing.java | 8 +-
.../datastructures/heaps/FibonacciHeap.java | 4 +-
.../datastructures/heaps/LeftistHeap.java | 16 ++-
.../datastructures/heaps/MaxHeap.java | 4 +-
.../datastructures/heaps/MinHeap.java | 4 +-
.../datastructures/queues/CircularQueue.java | 3 +-
.../datastructures/queues/LinkedQueue.java | 16 ++-
.../datastructures/queues/PriorityQueues.java | 8 +-
.../datastructures/trees/AVLSimple.java | 30 +++--
.../trees/InorderTraversal.java | 4 +-
.../datastructures/trees/KDTree.java | 113 +++++++++++++-----
.../datastructures/trees/LazySegmentTree.java | 40 +++++--
.../trees/PreOrderTraversal.java | 12 +-
.../datastructures/trees/SameTreesCheck.java | 12 +-
.../dynamicprogramming/KadaneAlgorithm.java | 4 +-
.../OptimalJobScheduling.java | 20 ++--
.../dynamicprogramming/SubsetCount.java | 16 ++-
.../dynamicprogramming/Tribonacci.java | 8 +-
.../thealgorithms/geometry/GrahamScan.java | 42 ++++---
.../com/thealgorithms/io/BufferedReader.java | 30 +++--
.../com/thealgorithms/maths/AliquotSum.java | 8 +-
.../maths/AutomorphicNumber.java | 12 +-
.../thealgorithms/maths/HarshadNumber.java | 8 +-
.../thealgorithms/maths/KaprekarNumbers.java | 8 +-
.../maths/MillerRabinPrimalityCheck.java | 37 ++++--
.../thealgorithms/maths/PascalTriangle.java | 7 +-
.../thealgorithms/maths/PerfectNumber.java | 12 +-
.../maths/SumWithoutArithmeticOperators.java | 4 +-
.../java/com/thealgorithms/others/CRC16.java | 4 +-
...imumSumOfDistinctSubarraysWithLengthK.java | 4 +-
.../scheduling/RRScheduling.java | 4 +-
.../searches/BinarySearch2dArray.java | 32 +++--
.../com/thealgorithms/searches/KMPSearch.java | 5 +-
.../searches/OrderAgnosticBinarySearch.java | 23 ++--
.../thealgorithms/searches/QuickSelect.java | 4 +-
.../searches/RabinKarpAlgorithm.java | 12 +-
.../searches/RecursiveBinarySearch.java | 5 +-
.../sorts/DualPivotQuickSort.java | 12 +-
.../thealgorithms/sorts/InsertionSort.java | 11 +-
.../com/thealgorithms/sorts/LinkListSort.java | 44 ++++---
.../thealgorithms/sorts/PigeonholeSort.java | 4 +-
.../sorts/SortUtilsRandomGenerator.java | 4 +-
.../com/thealgorithms/sorts/StrandSort.java | 9 +-
.../thealgorithms/sorts/TopologicalSort.java | 4 +-
.../stacks/NextSmallerElement.java | 4 +-
.../thealgorithms/stacks/PostfixToInfix.java | 24 +++-
.../com/thealgorithms/strings/Anagrams.java | 4 +-
.../strings/LongestNonRepeativeSubstring.java | 25 ++--
.../com/thealgorithms/strings/MyAtoi.java | 4 +-
.../com/thealgorithms/strings/Pangram.java | 7 +-
.../strings/ValidParentheses.java | 12 +-
.../strings/zigZagPattern/ZigZagPattern.java | 10 +-
.../buffers/CircularBufferTest.java | 32 +++--
.../queues/LinkedQueueTest.java | 8 +-
.../trees/LazySegmentTreeTest.java | 3 +-
.../thealgorithms/io/BufferedReaderTest.java | 4 +-
.../misc/MedianOfRunningArrayTest.java | 4 +-
68 files changed, 627 insertions(+), 259 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index b65291b8ffa8..48c8a4f1f377 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -155,7 +155,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java
index 80c11ce737fa..bf2a672a0ef8 100644
--- a/src/main/java/com/thealgorithms/backtracking/Combination.java
+++ b/src/main/java/com/thealgorithms/backtracking/Combination.java
@@ -43,7 +43,9 @@ public static List> combination(T[] arr, int n) {
* @param the type of elements in the array.
*/
private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) {
- if (index + length - currSet.size() > arr.length) return;
+ if (index + length - currSet.size() > arr.length) {
+ return;
+ }
if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) {
currSet.add(arr[i]);
diff --git a/src/main/java/com/thealgorithms/backtracking/MColoring.java b/src/main/java/com/thealgorithms/backtracking/MColoring.java
index 20c42e59e8a1..f069e46cc627 100644
--- a/src/main/java/com/thealgorithms/backtracking/MColoring.java
+++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java
@@ -59,7 +59,9 @@ static int possiblePaint(ArrayList nodes, int n, int m) {
// If number of colors used exceeds m,
// return 0
maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color));
- if (maxColors > m) return 0;
+ if (maxColors > m) {
+ return 0;
+ }
// If the adjacent node is not visited,
// mark it visited and push it in queue
diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
index 4ab81bfd7d67..f3a5b0433727 100644
--- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java
+++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
@@ -51,7 +51,9 @@ private boolean doDFS(int x, int y, int nextIdx) {
int yi = y + dy[i];
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
boolean exists = doDFS(xi, yi, nextIdx + 1);
- if (exists) return true;
+ if (exists) {
+ return true;
+ }
}
}
visited[x][y] = false;
@@ -66,7 +68,9 @@ public boolean exist(char[][] board, String word) {
if (board[i][j] == word.charAt(0)) {
visited = new boolean[board.length][board[0].length];
boolean exists = doDFS(i, j, 1);
- if (exists) return true;
+ if (exists) {
+ return true;
+ }
}
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index a8fa6fc56088..f6a0a3753e9b 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -1104,7 +1104,9 @@ private String hexToBin(String hex) {
private String binToHex(String binary) {
long num = Long.parseUnsignedLong(binary, 2);
String hex = Long.toHexString(num);
- while (hex.length() < (binary.length() / 4)) hex = "0" + hex;
+ while (hex.length() < (binary.length() / 4)) {
+ hex = "0" + hex;
+ }
return hex;
}
@@ -1120,7 +1122,9 @@ private String xor(String a, String b) {
a = hexToBin(a);
b = hexToBin(b);
String ans = "";
- for (int i = 0; i < a.length(); i++) ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
+ for (int i = 0; i < a.length(); i++) {
+ ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
+ }
ans = binToHex(ans);
return ans;
}
@@ -1202,7 +1206,9 @@ String encrypt(String plainText, String key) {
// generating key
keyGenerate(key);
- for (int i = 0; i < 16; i++) plainText = round(i, plainText);
+ for (int i = 0; i < 16; i++) {
+ plainText = round(i, plainText);
+ }
// postprocessing
String right = plainText.substring(0, 8);
@@ -1224,7 +1230,9 @@ String decrypt(String cipherText, String key) {
// generating key
keyGenerate(key);
- for (int i = 17; i > 1; i--) cipherText = round(i, cipherText);
+ for (int i = 17; i > 1; i--) {
+ cipherText = round(i, cipherText);
+ }
// postprocessing
String right = cipherText.substring(0, 8);
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
index 2e92498056ae..0b17a685bc57 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
@@ -31,7 +31,9 @@ public void reInitialize() {
}
public BitSet getNextKeyStream() {
- for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock();
+ 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) {
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
index 3cac558237c2..f96946c39490 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
@@ -19,7 +19,9 @@ public boolean clock() {
boolean result = false;
for (var register : registers) {
result ^= register.getLastBit();
- if (register.getClockBit() == majorityBit) register.clock();
+ if (register.getClockBit() == majorityBit) {
+ register.clock();
+ }
}
return result;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
index 63295b83abe6..15e9a0956226 100644
--- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
+++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
@@ -24,7 +24,9 @@ public boolean isFull() {
}
public Item get() {
- if (isEmpty()) return null;
+ if (isEmpty()) {
+ return null;
+ }
Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet();
@@ -32,7 +34,9 @@ public Item get() {
}
public boolean put(Item item) {
- if (isFull()) return false;
+ if (isFull()) {
+ return false;
+ }
buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet();
@@ -49,7 +53,9 @@ private static class CircularPointer {
}
public int getAndIncrement() {
- if (pointer == max) pointer = 0;
+ if (pointer == max) {
+ pointer = 0;
+ }
int tmp = pointer;
pointer++;
return tmp;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
index c24046f510af..7c0c0b2bee78 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
@@ -127,7 +127,9 @@ public void findStronglyConnectedComponents(int v, List> transpose
private void dfs(int node, int[] vis, List> list) {
vis[node] = 1;
for (Integer neighbour : list.get(node)) {
- if (vis[neighbour] == 0) dfs(neighbour, vis, list);
+ if (vis[neighbour] == 0) {
+ dfs(neighbour, vis, list);
+ }
}
stack.push(node);
}
@@ -136,7 +138,9 @@ private void dfs(int node, int[] vis, List> list) {
private void dfs2(int node, int[] vis, List> list) {
vis[node] = 1;
for (Integer neighbour : list.get(node)) {
- if (vis[neighbour] == 0) dfs2(neighbour, vis, list);
+ if (vis[neighbour] == 0) {
+ dfs2(neighbour, vis, list);
+ }
}
scc.add(node);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index 987e73a2a5d5..336e375f7d4e 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -82,7 +82,9 @@ public List> stronglyConnectedComponents(int v, List
Stack st = new Stack();
for (int i = 0; i < v; i++) {
- if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
+ if (insertionTime[i] == -1) {
+ stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
+ }
}
return sccList;
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
index ad273deaf4f0..e0b394b12bf6 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
@@ -68,10 +68,14 @@ private Node findEnd(Node n) {
public Node findKey(int key) {
if (!isEmpty()) {
Node temp = first;
- if (temp.getKey() == key) return temp;
+ if (temp.getKey() == key) {
+ return temp;
+ }
while ((temp = temp.getNext()) != null) {
- if (temp.getKey() == key) return temp;
+ if (temp.getKey() == key) {
+ return temp;
+ }
}
}
return null;
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
index b48502b51d08..a67968d7e659 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
@@ -188,12 +188,14 @@ public int findKeyInTable(int key) {
throw new IllegalArgumentException("Table is empty");
}
- if (Objects.equals(buckets[hash], wrappedInt)) return hash;
+ if (Objects.equals(buckets[hash], wrappedInt)) {
+ return hash;
+ }
hash = hashFunction2(key);
- if (!Objects.equals(buckets[hash], wrappedInt))
+ if (!Objects.equals(buckets[hash], wrappedInt)) {
throw new IllegalArgumentException("Key " + key + " not found in table");
- else {
+ } else {
return hash;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
index 4aa7db1956ea..4734483b518b 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -231,7 +231,9 @@ private void updateMin(HeapNode posMin) {
private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion
curr.mark();
- if (!curr.isRoot()) this.markedHeapNoodesCounter++;
+ if (!curr.isRoot()) {
+ this.markedHeapNoodesCounter++;
+ }
} else {
if (curr.isRoot()) {
return;
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
index 59cb9dfab700..ca18673c6724 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
@@ -56,9 +56,13 @@ public void merge(LeftistHeap h1) {
// Function merge with two Nodes a and b
public Node merge(Node a, Node b) {
- if (a == null) return b;
+ if (a == null) {
+ return b;
+ }
- if (b == null) return a;
+ if (b == null) {
+ return a;
+ }
// Violates leftist property, so must do a swap
if (a.element > b.element) {
@@ -93,7 +97,9 @@ public void insert(int a) {
// Returns and removes the minimum element in the heap
public int extractMin() {
// If is empty return -1
- if (isEmpty()) return -1;
+ if (isEmpty()) {
+ return -1;
+ }
int min = root.element;
root = merge(root.left, root.right);
@@ -109,7 +115,9 @@ public ArrayList inOrder() {
// Auxiliary function for in_order
private void inOrderAux(Node n, ArrayList lst) {
- if (n == null) return;
+ if (n == null) {
+ return;
+ }
inOrderAux(n.left, lst);
lst.add(n.element);
inOrderAux(n.right, lst);
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
index 9a584da0411c..067aae738914 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
@@ -98,11 +98,13 @@ public final void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
- if (maxHeap.isEmpty()) try {
+ if (maxHeap.isEmpty()) {
+ try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
+ }
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range");
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
index f7ff0ec5a73d..6e972205acfe 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
@@ -92,11 +92,13 @@ public final void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
- if (minHeap.isEmpty()) try {
+ if (minHeap.isEmpty()) {
+ try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
+ }
if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range");
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
index cd3761bdcf75..48d9ffe9a42a 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
@@ -23,8 +23,9 @@ public boolean isEmpty() {
public boolean isFull() {
if (topOfQueue + 1 == beginningOfQueue) {
return true;
- } else
+ } else {
return topOfQueue == size - 1 && beginningOfQueue == 0;
+ }
}
public void enQueue(int value) {
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
index 171f24e09396..5fba2ff6a69c 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
@@ -125,9 +125,13 @@ public T peekRear() {
*/
public T peek(int pos) {
- if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
+ if (pos > size) {
+ throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
+ }
Node node = front;
- while (pos-- > 0) node = node.next;
+ while (pos-- > 0) {
+ node = node.next;
+ }
return node.data;
}
@@ -170,14 +174,18 @@ public int size() {
* Clear all nodes in queue
*/
public void clear() {
- while (size > 0) dequeue();
+ while (size > 0) {
+ dequeue();
+ }
}
@Override
public String toString() {
StringJoiner join = new StringJoiner(", "); // separator of ', '
Node travel = front;
- while ((travel = travel.next) != null) join.add(String.valueOf(travel.data));
+ while ((travel = travel.next) != null) {
+ join.add(String.valueOf(travel.data));
+ }
return '[' + join.toString() + ']';
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
index 16a0c1673886..a5ca48670f2c 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
@@ -87,9 +87,13 @@ private void sink(int pos) {
while (2 * pos <= nItems) {
int current = 2 * pos; // Jump to the positon of child node
// Compare both the children for the greater one
- if (current < nItems && queueArray[current] < queueArray[current + 1]) current++;
+ if (current < nItems && queueArray[current] < queueArray[current + 1]) {
+ current++;
+ }
// If the parent node is greater, sink operation is complete. Break the loop
- if (queueArray[pos] >= queueArray[current]) break;
+ if (queueArray[pos] >= queueArray[current]) {
+ break;
+ }
// If not exchange the value of parent with child
int temp = queueArray[pos];
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
index 052da616fe8e..e0309122cc12 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
@@ -60,9 +60,13 @@ private Node insert(Node node, int item) {
node.height = Math.max(height(node.left), height(node.right)) + 1;
int bf = bf(node);
// LL case
- if (bf > 1 && item < node.left.data) return rightRotate(node);
+ if (bf > 1 && item < node.left.data) {
+ return rightRotate(node);
+ }
// RR case
- if (bf < -1 && item > node.right.data) return leftRotate(node);
+ if (bf < -1 && item > node.right.data) {
+ return leftRotate(node);
+ }
// RL case
if (bf < -1 && item < node.right.data) {
node.right = rightRotate(node.right);
@@ -84,18 +88,24 @@ public void display() {
private void display(Node node) {
String str = "";
- if (node.left != null)
+ if (node.left != null) {
str += node.left.data + "=>";
- else
+ } else {
str += "END=>";
+ }
str += node.data + "";
- if (node.right != null)
+ if (node.right != null) {
str += "<=" + node.right.data;
- else
+ } else {
str += "<=END";
+ }
System.out.println(str);
- if (node.left != null) display(node.left);
- if (node.right != null) display(node.right);
+ if (node.left != null) {
+ display(node.left);
+ }
+ if (node.right != null) {
+ display(node.right);
+ }
}
private int height(Node node) {
@@ -106,7 +116,9 @@ private int height(Node node) {
}
private int bf(Node node) {
- if (node == null) return 0;
+ if (node == null) {
+ return 0;
+ }
return height(node.left) - height(node.right);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
index 3bae17ed1bb8..5a001ff9ab9f 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
@@ -36,7 +36,9 @@ public static List recursiveInorder(BinaryTree.Node root) {
public static List iterativeInorder(BinaryTree.Node root) {
List result = new ArrayList<>();
- if (root == null) return result;
+ if (root == null) {
+ return result;
+ }
Deque stack = new ArrayDeque<>();
while (!stack.isEmpty() || root != null) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
index e5528c392bb8..5190e82f74ef 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
@@ -34,10 +34,15 @@ public class KDTree {
* @param points Array of initial points
*/
KDTree(Point[] points) {
- if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
+ if (points.length == 0) {
+ throw new IllegalArgumentException("Points array cannot be empty");
+ }
this.k = points[0].getDimension();
- for (Point point : points)
- if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
+ for (Point point : points) {
+ if (point.getDimension() != k) {
+ throw new IllegalArgumentException("Points must have the same dimension");
+ }
+ }
this.root = build(points, 0);
}
@@ -48,11 +53,16 @@ public class KDTree {
*
*/
KDTree(int[][] pointsCoordinates) {
- if (pointsCoordinates.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
+ if (pointsCoordinates.length == 0) {
+ throw new IllegalArgumentException("Points array cannot be empty");
+ }
this.k = pointsCoordinates[0].length;
Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
- for (Point point : points)
- if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
+ for (Point point : points) {
+ if (point.getDimension() != k) {
+ throw new IllegalArgumentException("Points must have the same dimension");
+ }
+ }
this.root = build(points, 0);
}
@@ -119,7 +129,9 @@ public static int comparableDistance(Point p1, Point p2) {
public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
int distance = 0;
for (int i = 0; i < p1.getDimension(); i++) {
- if (i == axis) continue;
+ if (i == axis) {
+ continue;
+ }
int t = p1.getCoordinate(i) - p2.getCoordinate(i);
distance += t * t;
}
@@ -164,10 +176,11 @@ public int getAxis() {
* @return The nearest child Node
*/
public Node getNearChild(Point point) {
- if (point.getCoordinate(axis) < this.point.getCoordinate(axis))
+ if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return left;
- else
+ } else {
return right;
+ }
}
/**
@@ -178,10 +191,11 @@ public Node getNearChild(Point point) {
* @return The farthest child Node
*/
public Node getFarChild(Point point) {
- if (point.getCoordinate(axis) < this.point.getCoordinate(axis))
+ if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return right;
- else
+ } else {
return left;
+ }
}
/**
@@ -207,9 +221,13 @@ public Node getRoot() {
* @return The root of the KDTree
*/
private Node build(Point[] points, int depth) {
- if (points.length == 0) return null;
+ if (points.length == 0) {
+ return null;
+ }
int axis = depth % k;
- if (points.length == 1) return new Node(points[0], axis);
+ if (points.length == 1) {
+ return new Node(points[0], axis);
+ }
Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis)));
int median = points.length >> 1;
Node node = new Node(points[median], axis);
@@ -225,7 +243,9 @@ private Node build(Point[] points, int depth) {
*
*/
public void insert(Point point) {
- if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
+ if (point.getDimension() != k) {
+ throw new IllegalArgumentException("Point has wrong dimension");
+ }
root = insert(root, point, 0);
}
@@ -240,11 +260,14 @@ public void insert(Point point) {
*/
private Node insert(Node root, Point point, int depth) {
int axis = depth % k;
- if (root == null) return new Node(point, axis);
- if (point.getCoordinate(axis) < root.getAxisCoordinate())
+ if (root == null) {
+ return new Node(point, axis);
+ }
+ if (point.getCoordinate(axis) < root.getAxisCoordinate()) {
root.left = insert(root.left, point, depth + 1);
- else
+ } else {
root.right = insert(root.right, point, depth + 1);
+ }
return root;
}
@@ -257,7 +280,9 @@ private Node insert(Node root, Point point, int depth) {
* @return The Node corresponding to the specified point
*/
public Optional search(Point point) {
- if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
+ if (point.getDimension() != k) {
+ throw new IllegalArgumentException("Point has wrong dimension");
+ }
return search(root, point);
}
@@ -270,8 +295,12 @@ public Optional search(Point point) {
* @return The Node corresponding to the specified point
*/
public Optional search(Node root, Point point) {
- if (root == null) return Optional.empty();
- if (root.point.equals(point)) return Optional.of(root);
+ if (root == null) {
+ return Optional.empty();
+ }
+ if (root.point.equals(point)) {
+ return Optional.of(root);
+ }
return search(root.getNearChild(point), point);
}
@@ -295,9 +324,13 @@ public Point findMin(int axis) {
* @return The Node with minimum value in the specified axis of the point
*/
public Node findMin(Node root, int axis) {
- if (root == null) return null;
+ if (root == null) {
+ return null;
+ }
if (root.getAxis() == axis) {
- if (root.left == null) return root;
+ if (root.left == null) {
+ return root;
+ }
return findMin(root.left, axis);
} else {
Node left = findMin(root.left, axis);
@@ -327,9 +360,13 @@ public Point findMax(int axis) {
* @return The Node with maximum value in the specified axis of the point
*/
public Node findMax(Node root, int axis) {
- if (root == null) return null;
+ if (root == null) {
+ return null;
+ }
if (root.getAxis() == axis) {
- if (root.right == null) return root;
+ if (root.right == null) {
+ return root;
+ }
return findMax(root.right, axis);
} else {
Node left = findMax(root.left, axis);
@@ -358,7 +395,9 @@ public void delete(Point point) {
* @return The new root of the subtree
*/
private Node delete(Node root, Node node) {
- if (root == null) return null;
+ if (root == null) {
+ return null;
+ }
if (root.equals(node)) {
if (root.right != null) {
Node min = findMin(root.right, root.getAxis());
@@ -368,13 +407,15 @@ private Node delete(Node root, Node node) {
Node min = findMin(root.left, root.getAxis());
root.point = min.point;
root.left = delete(root.left, min);
- } else
+ } else {
return null;
+ }
}
- if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis()))
+ if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) {
root.left = delete(root.left, node);
- else
+ } else {
root.right = delete(root.right, node);
+ }
return root;
}
@@ -395,13 +436,21 @@ public Point findNearest(Point point) {
* @param nearest The nearest neighbor found so far.
* */
private Node findNearest(Node root, Point point, Node nearest) {
- if (root == null) return nearest;
- if (root.point.equals(point)) return root;
+ if (root == null) {
+ return nearest;
+ }
+ if (root.point.equals(point)) {
+ return root;
+ }
int distance = Point.comparableDistance(root.point, point);
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
- if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
+ if (distance < Point.comparableDistance(nearest.point, point)) {
+ nearest = root;
+ }
nearest = findNearest(root.getNearChild(point), point, nearest);
- if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) nearest = findNearest(root.getFarChild(point), point, nearest);
+ if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) {
+ nearest = findNearest(root.getFarChild(point), point, nearest);
+ }
return nearest;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
index 1d8febff4b5f..e7a8e23d6610 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
@@ -40,11 +40,19 @@ public void applyUpdate(int diff) {
* Shift the lazy value of this node to its children.
*/
public void shift() {
- if (lazy == 0) return;
- if (this.left == null && this.right == null) return;
+ if (lazy == 0) {
+ return;
+ }
+ if (this.left == null && this.right == null) {
+ return;
+ }
this.value += this.lazy;
- if (this.left != null) this.left.applyUpdate(this.lazy);
- if (this.right != null) this.right.applyUpdate(this.lazy);
+ if (this.left != null) {
+ this.left.applyUpdate(this.lazy);
+ }
+ if (this.right != null) {
+ this.right.applyUpdate(this.lazy);
+ }
this.lazy = 0;
}
@@ -56,8 +64,12 @@ public void shift() {
* @return The new Node.
*/
static Node merge(Node left, Node right) {
- if (left == null) return right;
- if (right == null) return left;
+ if (left == null) {
+ return right;
+ }
+ if (right == null) {
+ return left;
+ }
Node result = new Node(left.start, right.end, left.value + right.value);
result.left = left;
result.right = right;
@@ -97,7 +109,9 @@ public LazySegmentTree(int[] array) {
* @return The root of the new LazySegmentTree.
*/
private Node buildTree(int[] array, int start, int end) {
- if (end - start < 2) return new Node(start, end, array[start]);
+ if (end - start < 2) {
+ return new Node(start, end, array[start]);
+ }
int mid = (start + end) >> 1;
Node left = buildTree(array, start, mid);
Node right = buildTree(array, mid, end);
@@ -117,7 +131,9 @@ private void updateRange(int left, int right, int diff, Node curr) {
curr.applyUpdate(diff);
return;
}
- if (left >= curr.end || right <= curr.start) return;
+ if (left >= curr.end || right <= curr.start) {
+ return;
+ }
curr.shift();
updateRange(left, right, diff, curr.left);
updateRange(left, right, diff, curr.right);
@@ -133,8 +149,12 @@ private void updateRange(int left, int right, int diff, Node curr) {
* @return The Node representing the sum of the given range.
*/
private Node getRange(int left, int right, Node curr) {
- if (left <= curr.start && curr.end <= right) return curr;
- if (left >= curr.end || right <= curr.start) return null;
+ if (left <= curr.start && curr.end <= right) {
+ return curr;
+ }
+ if (left >= curr.end || right <= curr.start) {
+ return null;
+ }
curr.shift();
return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right));
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
index 6a0eef369407..3aceac4d1852 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
@@ -36,15 +36,21 @@ public static List recursivePreOrder(BinaryTree.Node root) {
public static List iterativePreOrder(BinaryTree.Node root) {
List result = new ArrayList<>();
- if (root == null) return result;
+ if (root == null) {
+ return result;
+ }
Deque stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
BinaryTree.Node node = stack.pop();
result.add(node.data);
- if (node.right != null) stack.push(node.right);
- if (node.left != null) stack.push(node.left);
+ if (node.right != null) {
+ stack.push(node.right);
+ }
+ if (node.left != null) {
+ stack.push(node.left);
+ }
}
return result;
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
index 883eadd1840a..cff27c12f1ca 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
@@ -52,16 +52,22 @@ public static boolean check(BinaryTree.Node p, BinaryTree.Node q) {
BinaryTree.Node second = q2.poll();
// check that some node can be null
// if the check is true: both nodes are null or both nodes are not null
- if (!equalNodes(first, second)) return false;
+ if (!equalNodes(first, second)) {
+ return false;
+ }
if (first != null) {
- if (!equalNodes(first.left, second.left)) return false;
+ if (!equalNodes(first.left, second.left)) {
+ return false;
+ }
if (first.left != null) {
q1.add(first.left);
q2.add(second.left);
}
- if (!equalNodes(first.right, second.right)) return false;
+ if (!equalNodes(first.right, second.right)) {
+ return false;
+ }
if (first.right != null) {
q1.add(first.right);
q2.add(second.right);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
index de75126044ae..9962cca217a0 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
@@ -18,7 +18,9 @@ public static boolean maxSum(int[] a, int predictedAnswer) {
// running sum of all the indexs are stored
sum = Math.max(sum, runningSum);
// the max is stored inorder to the get the maximum sum
- if (runningSum < 0) runningSum = 0;
+ if (runningSum < 0) {
+ runningSum = 0;
+ }
// if running sum is negative then it is initialized to zero
}
// for-each loop is used to iterate over the array and find the maximum subarray sum
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
index 0840e08c531c..e31bb73096e8 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
@@ -69,19 +69,19 @@ private void calculateCost() {
*/
private int runningCost(int process, int machine) {
- if (process == 0) // refers to the first process,which does not require for a previous one
- // to have been executed
+ if (process == 0) { // refers to the first process,which does not require for a previous one
+ // to have been executed
return run[process][machine];
- else {
+ } else {
int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on
- // the Machine the previous one was executed
+ // the Machine the previous one was executed
- for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous
- // process to each and every Machine
+ for (int k = 0; k < numberMachines; k++) { // computes the cost of executing the previous
+ // process to each and every Machine
runningCosts[k] = cost[process - 1][k] + transfer[k][machine] + run[process][machine]; // transferring the result to our Machine and executing
- // the Process to our Machine
-
+ // the Process to our Machine
+ }
return findMin(runningCosts); // returns the minimum running cost
}
}
@@ -98,7 +98,9 @@ private int findMin(int[] costArr) {
for (int i = 1; i < costArr.length; i++) {
- if (costArr[i] < costArr[min]) min = i;
+ if (costArr[i] < costArr[min]) {
+ min = i;
+ }
}
return costArr[min];
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
index af31294f7e0e..cbe3ccae4ac7 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
@@ -29,12 +29,16 @@ public static int getCount(int[] arr, int target) {
for (int i = 0; i < n; i++) {
dp[i][0] = 1;
}
- if (arr[0] <= target) dp[0][arr[0]] = 1;
+ if (arr[0] <= target) {
+ dp[0][arr[0]] = 1;
+ }
for (int t = 1; t <= target; t++) {
for (int idx = 1; idx < n; idx++) {
int notpick = dp[idx - 1][t];
int pick = 0;
- if (arr[idx] <= t) pick += dp[idx - 1][target - t];
+ if (arr[idx] <= t) {
+ pick += dp[idx - 1][target - t];
+ }
dp[idx][target] = pick + notpick;
}
}
@@ -52,14 +56,18 @@ public static int getCountSO(int[] arr, int target) {
int n = arr.length;
int[] prev = new int[target + 1];
prev[0] = 1;
- if (arr[0] <= target) prev[arr[0]] = 1;
+ if (arr[0] <= target) {
+ prev[arr[0]] = 1;
+ }
for (int ind = 1; ind < n; ind++) {
int[] cur = new int[target + 1];
cur[0] = 1;
for (int t = 1; t <= target; t++) {
int notTaken = prev[t];
int taken = 0;
- if (arr[ind] <= t) taken = prev[t - arr[ind]];
+ if (arr[ind] <= t) {
+ taken = prev[t - arr[ind]];
+ }
cur[t] = notTaken + taken;
}
prev = cur;
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
index 407566f481a0..3ff6cc620236 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
@@ -15,8 +15,12 @@ private Tribonacci() {
* @return the n-th Tribonacci number
*/
public static int compute(int n) {
- if (n == 0) return 0;
- if (n == 1 || n == 2) return 1;
+ if (n == 0) {
+ return 0;
+ }
+ if (n == 1 || n == 2) {
+ return 1;
+ }
int first = 0;
int second = 1;
diff --git a/src/main/java/com/thealgorithms/geometry/GrahamScan.java b/src/main/java/com/thealgorithms/geometry/GrahamScan.java
index 4f4aebaed971..2773d03b4769 100644
--- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java
+++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java
@@ -32,13 +32,21 @@ public GrahamScan(Point[] points) {
// find index of first point not equal to a[0] (indexPoint1) and the first point that's not
// collinear with either (indexPoint2).
int indexPoint1;
- for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++)
- if (!points[0].equals(points[indexPoint1])) break;
- if (indexPoint1 == points.length) return;
+ for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) {
+ if (!points[0].equals(points[indexPoint1])) {
+ break;
+ }
+ }
+ if (indexPoint1 == points.length) {
+ return;
+ }
int indexPoint2;
- for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++)
- if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) break;
+ for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) {
+ if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) {
+ break;
+ }
+ }
hull.push(points[indexPoint2 - 1]);
// Now we simply add the point to the stack based on the orientation.
@@ -57,7 +65,9 @@ public GrahamScan(Point[] points) {
*/
public Iterable hull() {
Stack s = new Stack<>();
- for (Point p : hull) s.push(p);
+ for (Point p : hull) {
+ s.push(p);
+ }
return s;
}
@@ -112,7 +122,9 @@ public static int orientation(Point a, Point b, Point c) {
*/
public int compareTo(Point p2) {
int res = Integer.compare(this.y, p2.y);
- if (res == 0) res = Integer.compare(this.x, p2.x);
+ if (res == 0) {
+ res = Integer.compare(this.x, p2.x);
+ }
return res;
}
@@ -133,19 +145,21 @@ public int compare(Point p1, Point p2) {
int dx2 = p2.x - x;
int dy2 = p2.y - y;
- if (dy1 >= 0 && dy2 < 0)
+ if (dy1 >= 0 && dy2 < 0) {
return -1; // q1 above; q2 below
- else if (dy2 >= 0 && dy1 < 0)
+ } else if (dy2 >= 0 && dy1 < 0) {
return +1; // q1 below; q2 above
- else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
- if (dx1 >= 0 && dx2 < 0)
+ } else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
+ if (dx1 >= 0 && dx2 < 0) {
return -1;
- else if (dx2 >= 0 && dx1 < 0)
+ } else if (dx2 >= 0 && dx1 < 0) {
return +1;
- else
+ } else {
return 0;
- } else
+ }
+ } else {
return -orientation(Point.this, p1, p2); // both above or below
+ }
}
}
diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java
index fa0237a48049..66673fe281ae 100644
--- a/src/main/java/com/thealgorithms/io/BufferedReader.java
+++ b/src/main/java/com/thealgorithms/io/BufferedReader.java
@@ -44,7 +44,9 @@ public BufferedReader(InputStream input) throws IOException {
public BufferedReader(InputStream input, int bufferSize) throws IOException {
this.input = input;
- if (input.available() == -1) throw new IOException("Empty or already closed stream provided");
+ if (input.available() == -1) {
+ throw new IOException("Empty or already closed stream provided");
+ }
this.bufferSize = bufferSize;
buffer = new byte[bufferSize];
@@ -55,7 +57,9 @@ public BufferedReader(InputStream input, int bufferSize) throws IOException {
*/
public int read() throws IOException {
if (needsRefill()) {
- if (foundEof) return -1;
+ if (foundEof) {
+ return -1;
+ }
// the buffer is empty, or the buffer has
// been completely read and needs to be refilled
refill();
@@ -69,10 +73,11 @@ public int read() throws IOException {
public int available() throws IOException {
int available = input.available();
- if (needsRefill())
+ if (needsRefill()) {
// since the block is already empty,
// we have no responsibility yet
return available;
+ }
return bufferPos - posRead + available;
}
@@ -90,10 +95,14 @@ public int peek() throws IOException {
public int peek(int n) throws IOException {
int available = available();
- if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
+ if (n >= available) {
+ throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
+ }
pushRefreshData();
- if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
+ if (n >= bufferSize) {
+ throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
+ }
return buffer[n];
}
@@ -105,7 +114,9 @@ public int peek(int n) throws IOException {
*/
private void pushRefreshData() throws IOException {
- for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i];
+ for (int i = posRead, j = 0; i < bufferSize; i++, j++) {
+ buffer[j] = buffer[i];
+ }
bufferPos -= posRead;
posRead = 0;
@@ -127,11 +138,12 @@ public byte[] readBlock() throws IOException {
byte[] cloned = new byte[bufferSize];
// arraycopy() function is better than clone()
- if (bufferPos >= 0)
+ if (bufferPos >= 0) {
System.arraycopy(buffer, 0, cloned, 0,
// important to note that, bufferSize does not stay constant
// once the class is defined. See justRefill() function
bufferSize);
+ }
// we assume that already a chunk
// has been read
refill();
@@ -168,7 +180,9 @@ private void justRefill() throws IOException {
}
private void assertStreamOpen() {
- if (input == null) throw new IllegalStateException("Input Stream already closed!");
+ if (input == null) {
+ throw new IllegalStateException("Input Stream already closed!");
+ }
}
public void close() throws IOException {
diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java
index 5a5555777425..0dbc58bed605 100644
--- a/src/main/java/com/thealgorithms/maths/AliquotSum.java
+++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java
@@ -34,7 +34,9 @@ public static int getAliquotValue(int number) {
* @return aliquot sum of given {@code number}
*/
public static int getAliquotSum(int n) {
- if (n <= 0) return -1;
+ if (n <= 0) {
+ return -1;
+ }
int sum = 1;
double root = Math.sqrt(n);
/*
@@ -53,7 +55,9 @@ public static int getAliquotSum(int n) {
}
// if n is a perfect square then its root was added twice in above loop, so subtracting root
// from sum
- if (root == (int) root) sum -= root;
+ if (root == (int) root) {
+ sum -= root;
+ }
return sum;
}
}
diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
index 560ce3aabd1a..03c8a8989bb2 100644
--- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
+++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
@@ -22,7 +22,9 @@ private AutomorphicNumber() {
* {@code false}
*/
public static boolean isAutomorphic(long n) {
- if (n < 0) return false;
+ if (n < 0) {
+ return false;
+ }
long square = n * n; // Calculating square of the number
long t = n;
long numberOfdigits = 0;
@@ -42,7 +44,9 @@ public static boolean isAutomorphic(long n) {
* {@code false}
*/
public static boolean isAutomorphic2(long n) {
- if (n < 0) return false;
+ if (n < 0) {
+ return false;
+ }
long square = n * n; // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
@@ -56,7 +60,9 @@ public static boolean isAutomorphic2(long n) {
*/
public static boolean isAutomorphic3(String s) {
BigInteger n = new BigInteger(s);
- if (n.signum() == -1) return false; // if number is negative, return false
+ if (n.signum() == -1) {
+ return false; // if number is negative, return false
+ }
BigInteger square = n.multiply(n); // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
diff --git a/src/main/java/com/thealgorithms/maths/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java
index 0b1ba1285c4d..5792e925a8aa 100644
--- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java
+++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java
@@ -14,7 +14,9 @@ private HarshadNumber() {
* {@code false}
*/
public static boolean isHarshad(long n) {
- if (n <= 0) return false;
+ if (n <= 0) {
+ return false;
+ }
long t = n;
long sumOfDigits = 0;
@@ -35,7 +37,9 @@ public static boolean isHarshad(long n) {
*/
public static boolean isHarshad(String s) {
final Long n = Long.valueOf(s);
- if (n <= 0) return false;
+ if (n <= 0) {
+ return false;
+ }
int sumOfDigits = 0;
for (char ch : s.toCharArray()) {
diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java
index f025f86682a2..eb9750f9ce08 100644
--- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java
+++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java
@@ -16,11 +16,15 @@ private KaprekarNumbers() {
// Provides a list of kaprekarNumber in a range
public static List kaprekarNumberInRange(long start, long end) throws Exception {
long n = end - start;
- if (n < 0) throw new Exception("Invalid range");
+ if (n < 0) {
+ throw new Exception("Invalid range");
+ }
ArrayList list = new ArrayList<>();
for (long i = start; i <= end; i++) {
- if (isKaprekarNumber(i)) list.add(i);
+ if (isKaprekarNumber(i)) {
+ list.add(i);
+ }
}
return list;
diff --git a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
index e25836f713a9..f889213abfcb 100644
--- a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
+++ b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java
@@ -20,7 +20,9 @@ private MillerRabinPrimalityCheck() {
*/
public static boolean millerRabin(long n, int k) { // returns true if n is probably prime, else returns false.
- if (n < 4) return n == 2 || n == 3;
+ if (n < 4) {
+ return n == 2 || n == 3;
+ }
int s = 0;
long d = n - 1;
@@ -31,13 +33,17 @@ public static boolean millerRabin(long n, int k) { // returns true if n is proba
Random rnd = new Random();
for (int i = 0; i < k; i++) {
long a = 2 + rnd.nextLong(n) % (n - 3);
- if (checkComposite(n, a, d, s)) return false;
+ if (checkComposite(n, a, d, s)) {
+ return false;
+ }
}
return true;
}
public static boolean deterministicMillerRabin(long n) { // returns true if n is prime, else returns false.
- if (n < 2) return false;
+ if (n < 2) {
+ return false;
+ }
int r = 0;
long d = n - 1;
@@ -47,8 +53,12 @@ public static boolean deterministicMillerRabin(long n) { // returns true if n is
}
for (int a : new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
- if (n == a) return true;
- if (checkComposite(n, a, d, r)) return false;
+ if (n == a) {
+ return true;
+ }
+ if (checkComposite(n, a, d, r)) {
+ return false;
+ }
}
return true;
}
@@ -66,10 +76,14 @@ public static boolean deterministicMillerRabin(long n) { // returns true if n is
*/
private static boolean checkComposite(long n, long a, long d, int s) {
long x = powerModP(a, d, n);
- if (x == 1 || x == n - 1) return false;
+ if (x == 1 || x == n - 1) {
+ return false;
+ }
for (int r = 1; r < s; r++) {
x = powerModP(x, 2, n);
- if (x == n - 1) return false;
+ if (x == n - 1) {
+ return false;
+ }
}
return true;
}
@@ -79,11 +93,14 @@ private static long powerModP(long x, long y, long p) {
x = x % p; // Update x if it is more than or equal to p
- if (x == 0) return 0; // In case x is divisible by p;
-
+ if (x == 0) {
+ return 0; // In case x is divisible by p;
+ }
while (y > 0) {
// If y is odd, multiply x with result
- if ((y & 1) == 1) res = multiplyModP(res, x, p);
+ if ((y & 1) == 1) {
+ res = multiplyModP(res, x, p);
+ }
// y must be even now
y = y >> 1; // y = y/2
diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java
index ef6aa41d6e53..95f92fbe1b49 100644
--- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java
+++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java
@@ -52,10 +52,11 @@ public static int[][] pascal(int n) {
*/
for (int i = 0; i <= line; i++) {
// First and last values in every row are 1
- if (line == i || i == 0) arr[line][i] = 1;
- // The rest elements are sum of values just above and left of above
- else
+ if (line == i || i == 0) {
+ arr[line][i] = 1;
+ } else {
arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i];
+ }
}
}
diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java
index 49afd23f91bf..2a935b067094 100644
--- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java
+++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java
@@ -19,7 +19,9 @@ private PerfectNumber() {
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber(int number) {
- if (number <= 0) return false;
+ if (number <= 0) {
+ return false;
+ }
int sum = 0;
/* sum of its positive divisors */
for (int i = 1; i < number; ++i) {
@@ -37,7 +39,9 @@ public static boolean isPerfectNumber(int number) {
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber2(int n) {
- if (n <= 0) return false;
+ if (n <= 0) {
+ return false;
+ }
int sum = 1;
double root = Math.sqrt(n);
@@ -58,7 +62,9 @@ public static boolean isPerfectNumber2(int n) {
// if n is a perfect square then its root was added twice in above loop, so subtracting root
// from sum
- if (root == (int) root) sum -= root;
+ if (root == (int) root) {
+ sum -= root;
+ }
return sum == n;
}
diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java
index 8bc1afbe8771..5369182a0a94 100644
--- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java
+++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java
@@ -12,7 +12,9 @@ public class SumWithoutArithmeticOperators {
*/
public int getSum(int a, int b) {
- if (b == 0) return a;
+ if (b == 0) {
+ return a;
+ }
int sum = a ^ b;
int carry = (a & b) << 1;
return getSum(sum, carry);
diff --git a/src/main/java/com/thealgorithms/others/CRC16.java b/src/main/java/com/thealgorithms/others/CRC16.java
index 85e5cd2c13ae..847ce8edab0a 100644
--- a/src/main/java/com/thealgorithms/others/CRC16.java
+++ b/src/main/java/com/thealgorithms/others/CRC16.java
@@ -21,7 +21,9 @@ public static String crc16(String message) {
boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
- if (c15 ^ bit) crc ^= polynomial;
+ if (c15 ^ bit) {
+ crc ^= polynomial;
+ }
}
}
crc &= 0xffff;
diff --git a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java
index 0bafc435aa75..5aa25812dcc2 100644
--- a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java
+++ b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java
@@ -24,7 +24,9 @@ private MaximumSumOfDistinctSubarraysWithLengthK() {
* @return the maximum sum of distinct subarray of size K.
*/
public static long maximumSubarraySum(int k, int... nums) {
- if (nums.length < k) return 0;
+ if (nums.length < k) {
+ return 0;
+ }
long max = 0; // this will store the max sum which will be our result
long s = 0; // this will store the sum of every k elements which can be used to compare with
// max
diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
index 991c9a4f6148..110c97416a42 100644
--- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
+++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
@@ -79,7 +79,9 @@ private void evaluateTurnAroundTime() {
// If the current process has burst time remaining, push the process into the queue
// again.
- if (remainingBurstTime[index] > 0) queue.add(index);
+ if (remainingBurstTime[index] > 0) {
+ queue.add(index);
+ }
// If the queue is empty, pick the first process from the list that is not completed.
if (queue.isEmpty()) {
diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
index 40b3cd0c20e3..53f5d7c8434e 100644
--- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
+++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
@@ -29,47 +29,57 @@ static int[] binarySearch(int[][] arr, int target) {
if (arr[midRow][midCol] == target) {
return new int[] {midRow, midCol};
- } else if (arr[midRow][midCol] < target)
+ } else if (arr[midRow][midCol] < target) {
startRow = midRow;
- else
+ } else {
endRow = midRow;
+ }
}
/*
if the above search fails to find the target element, these conditions will be used to
find the target element, which further uses the binary search algorithm in the places
which were left unexplored.
*/
- if (arr[startRow][midCol] == target)
+ if (arr[startRow][midCol] == target) {
return new int[] {
startRow,
midCol,
};
+ }
- if (arr[endRow][midCol] == target) return new int[] {endRow, midCol};
+ if (arr[endRow][midCol] == target) {
+ return new int[] {endRow, midCol};
+ }
- if (target <= arr[startRow][midCol - 1]) return binarySearch(arr, target, startRow, 0, midCol - 1);
+ if (target <= arr[startRow][midCol - 1]) {
+ return binarySearch(arr, target, startRow, 0, midCol - 1);
+ }
- if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) return binarySearch(arr, target, startRow, midCol + 1, colCount - 1);
+ if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) {
+ return binarySearch(arr, target, startRow, midCol + 1, colCount - 1);
+ }
- if (target <= arr[endRow][midCol - 1])
+ if (target <= arr[endRow][midCol - 1]) {
return binarySearch(arr, target, endRow, 0, midCol - 1);
- else
+ } else {
return binarySearch(arr, target, endRow, midCol + 1, colCount - 1);
+ }
}
static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) {
while (colStart <= colEnd) {
int midIndex = colStart + (colEnd - colStart) / 2;
- if (arr[row][midIndex] == target)
+ if (arr[row][midIndex] == target) {
return new int[] {
row,
midIndex,
};
- else if (arr[row][midIndex] < target)
+ } else if (arr[row][midIndex] < target) {
colStart = midIndex + 1;
- else
+ } else {
colEnd = midIndex - 1;
+ }
}
return new int[] {-1, -1};
diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java
index 3648a4b08b86..8bf2754ff8f7 100644
--- a/src/main/java/com/thealgorithms/searches/KMPSearch.java
+++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java
@@ -32,10 +32,11 @@ int kmpSearch(String pat, String txt) {
else if (i < n && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
- if (j != 0)
+ if (j != 0) {
j = lps[j - 1];
- else
+ } else {
i = i + 1;
+ }
}
}
System.out.println("No pattern found");
diff --git a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
index cdd256150871..d85cb37c4427 100644
--- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
@@ -24,22 +24,23 @@ static int binSearchAlgo(int[] arr, int start, int end, int target) {
int middle = start + (end - start) / 2;
// Check if the desired element is present at the middle position
- if (arr[middle] == target) return middle; // returns the index of the middle element
-
- // Ascending order
+ if (arr[middle] == target) {
+ return middle; // returns the index of the middle element
+ }
if (ascOrd) {
- if (arr[middle] < target)
+ // Ascending order
+ if (arr[middle] < target) {
start = middle + 1;
- else
+ } else {
end = middle - 1;
- }
-
- // Descending order
- else {
- if (arr[middle] > target)
+ }
+ } else {
+ // Descending order
+ if (arr[middle] > target) {
start = middle + 1;
- else
+ } else {
end = middle - 1;
+ }
}
}
// Element is not present
diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java
index 97eab4bb4046..c89abb00e9da 100644
--- a/src/main/java/com/thealgorithms/searches/QuickSelect.java
+++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java
@@ -56,7 +56,9 @@ private static > int selectIndex(List list, int n) {
private static > int selectIndex(List list, int left, int right, int n) {
while (true) {
- if (left == right) return left;
+ if (left == right) {
+ return left;
+ }
int pivotIndex = pivot(list, left, right);
pivotIndex = partition(list, left, right, pivotIndex, n);
if (n == pivotIndex) {
diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
index cc8387f6c4f3..81e16dbbbf07 100644
--- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
+++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
@@ -18,7 +18,9 @@ public static int search(String pattern, String text, int primeNumber) {
int h = 1;
// The value of h would be "pow(d, patternLength-1)%primeNumber"
- for (int i = 0; i < patternLength - 1; i++) h = (h * ALPHABET_SIZE) % primeNumber;
+ for (int i = 0; i < patternLength - 1; i++) {
+ h = (h * ALPHABET_SIZE) % primeNumber;
+ }
// Calculate the hash value of pattern and first
// window of text
@@ -37,7 +39,9 @@ public static int search(String pattern, String text, int primeNumber) {
if (hashForPattern == hashForText) {
/* Check for characters one by one */
for (j = 0; j < patternLength; j++) {
- if (text.charAt(i + j) != pattern.charAt(j)) break;
+ if (text.charAt(i + j) != pattern.charAt(j)) {
+ break;
+ }
}
// if hashForPattern == hashForText and pattern[0...patternLength-1] = text[i, i+1, ...i+patternLength-1]
@@ -53,7 +57,9 @@ public static int search(String pattern, String text, int primeNumber) {
hashForText = (ALPHABET_SIZE * (hashForText - text.charAt(i) * h) + text.charAt(i + patternLength)) % primeNumber;
// handling negative hashForText
- if (hashForText < 0) hashForText = (hashForText + primeNumber);
+ if (hashForText < 0) {
+ hashForText = (hashForText + primeNumber);
+ }
}
}
return index; // return -1 if pattern does not found
diff --git a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java
index 6c6284e28019..daf0c12c0978 100644
--- a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java
@@ -67,10 +67,11 @@ public static void main(String[] args) {
RecursiveBinarySearch searcher = new RecursiveBinarySearch<>();
int res = searcher.find(a, t);
- if (res == -1)
+ if (res == -1) {
System.out.println("Element not found in the array.");
- else
+ } else {
System.out.println("Element found at index " + res);
+ }
}
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
index 60cb5aa7aa69..5a6ba256521f 100644
--- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
@@ -44,7 +44,9 @@ private static > void dualPivotQuicksort(T[] array, int
* @param right The last index of an array Finds the partition index of an array
*/
private static > int[] partition(T[] array, int left, int right) {
- if (array[left].compareTo(array[right]) > 0) swap(array, left, right);
+ if (array[left].compareTo(array[right]) > 0) {
+ swap(array, left, right);
+ }
T pivot1 = array[left];
T pivot2 = array[right];
@@ -61,11 +63,15 @@ private static > int[] partition(T[] array, int left, in
// If element is greater or equal to pivot2
else if (array[less].compareTo(pivot2) >= 0) {
- while (less < great && array[great].compareTo(pivot2) > 0) great--;
+ while (less < great && array[great].compareTo(pivot2) > 0) {
+ great--;
+ }
swap(array, less, great--);
- if (array[less].compareTo(pivot1) < 0) swap(array, less, left++);
+ if (array[less].compareTo(pivot1) < 0) {
+ swap(array, less, left++);
+ }
}
less++;
diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java
index 3b8c286515bc..36aba615ba94 100644
--- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java
+++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java
@@ -38,12 +38,17 @@ public > T[] sort(T[] array, int lo, int hi) {
public > T[] sentinelSort(T[] array) {
int minElemIndex = 0;
int n = array.length;
- if (n < 1) return array;
+ if (n < 1) {
+ return array;
+ }
// put the smallest element to the 0 position as a sentinel, which will allow us to avoid
// redundant comparisons like `j > 0` further
- for (int i = 1; i < n; i++)
- if (SortUtils.less(array[i], array[minElemIndex])) minElemIndex = i;
+ for (int i = 1; i < n; i++) {
+ if (SortUtils.less(array[i], array[minElemIndex])) {
+ minElemIndex = i;
+ }
+ }
SortUtils.swap(array, 0, minElemIndex);
for (int i = 2; i < n; i++) {
diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
index fdbfe3130e41..c9000f7e3778 100644
--- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java
+++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
@@ -30,10 +30,11 @@ public static boolean isSorted(int[] p, int option) {
// 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)
+ if (start == null) {
start = fresh;
- else
+ } else {
prev.next = fresh;
+ }
prev = fresh;
}
start = nm.sortByMergeSort(start);
@@ -58,10 +59,11 @@ public static boolean isSorted(int[] p, int option) {
// 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)
+ if (start1 == null) {
start1 = fresh1;
- else
+ } else {
prev1.next = fresh1;
+ }
prev1 = fresh1;
}
Task1 kk = new Task1();
@@ -87,10 +89,11 @@ public static boolean isSorted(int[] p, int option) {
// 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)
+ if (start2 == null) {
start2 = fresh2;
- else
+ } else {
prev2.next = fresh2;
+ }
prev2 = fresh2;
}
start2 = mm.sortByHeapSort(start2);
@@ -116,7 +119,9 @@ public static boolean isSorted(int[] p, int option) {
boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
- if (a[i] != b[i]) return false;
+ if (a[i] != b[i]) {
+ return false;
+ }
}
return true;
// Both the arrays are checked for equalness. If both are equal then true is
@@ -147,7 +152,9 @@ class Task {
private int[] a;
public Node sortByMergeSort(Node head) {
- if (head == null || head.next == null) return head;
+ if (head == null || head.next == null) {
+ return head;
+ }
int c = count(head);
a = new int[c];
// Array of size c is created
@@ -193,10 +200,11 @@ void task1(int[] n, int s, int m, int e) {
int j = m + 1;
int[] b = new int[e - s + 1];
while (i <= m && j <= e) {
- if (n[j] >= n[i])
+ if (n[j] >= n[i]) {
b[k++] = n[i++];
- else
+ } else {
b[k++] = n[j++];
+ }
}
// Smallest number is stored after checking from both the arrays
while (i <= m) {
@@ -215,7 +223,9 @@ void task1(int[] n, int s, int m, int e) {
class Task1 {
public Node sortByInsertionSort(Node head) {
- if (head == null || head.next == null) return head;
+ if (head == null || head.next == null) {
+ return head;
+ }
int c = count(head);
int[] a = new int[c];
// Array of size c is created
@@ -257,7 +267,9 @@ class Task2 {
private int[] a;
public Node sortByHeapSort(Node head) {
- if (head == null || head.next == null) return head;
+ if (head == null || head.next == null) {
+ return head;
+ }
int c = count(head);
a = new int[c];
// Array of size c is created
@@ -304,8 +316,12 @@ 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 (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];
diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
index 9c0ab45b6a3c..42fd026b117b 100644
--- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
+++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
@@ -12,7 +12,9 @@ public class PigeonholeSort {
void sort(Integer[] array) {
int maxElement = array[0];
for (int element : array) {
- if (element > maxElement) maxElement = element;
+ if (element > maxElement) {
+ maxElement = element;
+ }
}
int numOfPigeonholes = 1 + maxElement;
diff --git a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java
index b048d0245b64..ed2f538f4d89 100644
--- a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java
+++ b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java
@@ -22,7 +22,9 @@ private SortUtilsRandomGenerator() {
*/
public static Double[] generateArray(int size) {
Double[] arr = new Double[size];
- for (int i = 0; i < size; i++) arr[i] = generateDouble();
+ for (int i = 0; i < size; i++) {
+ arr[i] = generateDouble();
+ }
return arr;
}
diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java
index 7e2251d70640..51600812bbb1 100644
--- a/src/main/java/com/thealgorithms/sorts/StrandSort.java
+++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java
@@ -9,7 +9,9 @@ private StrandSort() {
// note: the input list is destroyed
public static > LinkedList strandSort(LinkedList list) {
- if (list.size() <= 1) return list;
+ if (list.size() <= 1) {
+ return list;
+ }
LinkedList result = new LinkedList();
while (list.size() > 0) {
@@ -31,10 +33,11 @@ private static > LinkedList merge(LinkedList<
LinkedList result = new LinkedList();
while (!left.isEmpty() && !right.isEmpty()) {
// change the direction of this comparison to change the direction of the sort
- if (left.peek().compareTo(right.peek()) <= 0)
+ if (left.peek().compareTo(right.peek()) <= 0) {
result.add(left.remove());
- else
+ } else {
result.add(right.remove());
+ }
}
result.addAll(left);
result.addAll(right);
diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
index dd3a763bb197..e4ed240a9947 100644
--- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
+++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
@@ -69,7 +69,9 @@ static class 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);
+ if (!next[0].isEmpty()) {
+ Collections.addAll(adj.get(label).next, next);
+ }
}
}
diff --git a/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java
index 4d37da0e7c31..6eae06ad7efc 100644
--- a/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java
+++ b/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java
@@ -51,7 +51,9 @@ public static int[] findNextSmallerElements(int[] array) {
Arrays.fill(result, -1);
for (int i = 0; i < array.length; i++) {
- while (!stack.empty() && stack.peek() >= array[i]) stack.pop();
+ while (!stack.empty() && stack.peek() >= array[i]) {
+ stack.pop();
+ }
if (stack.empty()) {
result[i] = -1;
} else {
diff --git a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java
index c69a511c2c17..118a3df381c9 100644
--- a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java
+++ b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java
@@ -35,11 +35,17 @@ public static boolean isOperator(char token) {
public static boolean isValidPostfixExpression(String postfix) {
/* Postfix expression length should NOT be less than 3 */
- if (postfix.length() < 3) return false;
+ if (postfix.length() < 3) {
+ return false;
+ }
/* First two characters should NOT be operators */
- if (isOperator(postfix.charAt(0))) return false;
- if (isOperator(postfix.charAt(1))) return false;
+ if (isOperator(postfix.charAt(0))) {
+ return false;
+ }
+ if (isOperator(postfix.charAt(1))) {
+ return false;
+ }
int operandCount = 0;
int operatorCount = 0;
@@ -51,14 +57,18 @@ public static boolean isValidPostfixExpression(String postfix) {
if (isOperator(token)) {
operatorCount++;
- if (operatorCount >= operandCount) return false;
+ if (operatorCount >= operandCount) {
+ return false;
+ }
} else {
if (operatorCount == 0) {
operandCount++;
continue;
}
- if (operandCount != operatorCount + 1) return false;
+ if (operandCount != operatorCount + 1) {
+ return false;
+ }
/* Operand count is set to 2 because:-
*
@@ -80,7 +90,9 @@ public static boolean isValidPostfixExpression(String postfix) {
public static String getPostfixToInfix(String postfix) {
String infix = "";
- if (postfix.isEmpty()) return infix;
+ if (postfix.isEmpty()) {
+ return infix;
+ }
/* Validate Postfix expression before proceeding with the Infix conversion */
if (!isValidPostfixExpression(postfix)) {
diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java
index 352d2308c5ea..106be5e1a596 100644
--- a/src/main/java/com/thealgorithms/strings/Anagrams.java
+++ b/src/main/java/com/thealgorithms/strings/Anagrams.java
@@ -96,7 +96,9 @@ boolean approach3(String s, String t) {
b[t.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
- if (a[i] != b[i]) return false;
+ if (a[i] != b[i]) {
+ return false;
+ }
}
return true;
}
diff --git a/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
index 140e668fc841..cc99a16facc3 100644
--- a/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
+++ b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java
@@ -16,20 +16,21 @@ public static int lengthOfLongestSubstring(String s) {
char temp = s.charAt(i);
// adding key to map if not present
- if (!map.containsKey(temp)) map.put(temp, 0);
- // checking if the first value is the dublicate value
- else if (s.charAt(start) == temp)
+ if (!map.containsKey(temp)) {
+ map.put(temp, 0);
+ } else if (s.charAt(start) == temp) {
start++;
- // checking if the previous value is dublicate value
- else if (s.charAt(i - 1) == temp) {
- if (max < map.size()) max = map.size();
+ } else if (s.charAt(i - 1) == temp) {
+ if (max < map.size()) {
+ max = map.size();
+ }
map = new HashMap<>();
start = i;
i--;
- }
- // last possible place where dublicate value can be is between start and i
- else {
- if (max < map.size()) max = map.size();
+ } else {
+ if (max < map.size()) {
+ max = map.size();
+ }
while (s.charAt(start) != temp) {
map.remove(s.charAt(start));
start++;
@@ -39,7 +40,9 @@ else if (s.charAt(i - 1) == temp) {
i++;
}
- if (max < map.size()) max = map.size();
+ if (max < map.size()) {
+ max = map.size();
+ }
return max;
}
}
diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java
index 0aed13f936a7..f58ab1acf8c5 100644
--- a/src/main/java/com/thealgorithms/strings/MyAtoi.java
+++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java
@@ -25,7 +25,9 @@ public static int myAtoi(String s) {
number = "0";
break;
}
- if (ch >= '0' && ch <= '9') number += ch;
+ if (ch >= '0' && ch <= '9') {
+ number += ch;
+ }
} else if (ch == '-' && !isDigit) {
number += "0";
negative = true;
diff --git a/src/main/java/com/thealgorithms/strings/Pangram.java b/src/main/java/com/thealgorithms/strings/Pangram.java
index e0989ce86715..01307b28f6c6 100644
--- a/src/main/java/com/thealgorithms/strings/Pangram.java
+++ b/src/main/java/com/thealgorithms/strings/Pangram.java
@@ -29,8 +29,11 @@ public static void main(String[] args) {
public static boolean isPangramUsingSet(String s) {
HashSet alpha = new HashSet<>();
s = s.trim().toLowerCase();
- for (int i = 0; i < s.length(); i++)
- if (s.charAt(i) != ' ') alpha.add(s.charAt(i));
+ for (int i = 0; i < s.length(); i++) {
+ if (s.charAt(i) != ' ') {
+ alpha.add(s.charAt(i));
+ }
+ }
return alpha.size() == 26;
}
diff --git a/src/main/java/com/thealgorithms/strings/ValidParentheses.java b/src/main/java/com/thealgorithms/strings/ValidParentheses.java
index 947a39da4bde..f4f3761b0495 100644
--- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java
+++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java
@@ -18,13 +18,19 @@ public static boolean isValid(String s) {
stack[head++] = c;
break;
case '}':
- if (head == 0 || stack[--head] != '{') return false;
+ if (head == 0 || stack[--head] != '{') {
+ return false;
+ }
break;
case ')':
- if (head == 0 || stack[--head] != '(') return false;
+ if (head == 0 || stack[--head] != '(') {
+ return false;
+ }
break;
case ']':
- if (head == 0 || stack[--head] != '[') return false;
+ if (head == 0 || stack[--head] != '[') {
+ return false;
+ }
break;
default:
throw new IllegalArgumentException("Unexpected character: " + c);
diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
index 3337f6eeff71..3f33fc17b9b0 100644
--- a/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
+++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java
@@ -5,7 +5,9 @@ private ZigZagPattern() {
}
public static String encode(String s, int numRows) {
- if (numRows < 2 || s.length() < numRows) return s;
+ if (numRows < 2 || s.length() < numRows) {
+ return s;
+ }
int start = 0;
int index = 0;
int height = 1;
@@ -18,11 +20,11 @@ public static String encode(String s, int numRows) {
boolean bool = true;
while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer);
- if (heightSpace == 0)
+ if (heightSpace == 0) {
pointer += depthSpace;
- else if (depthSpace == 0)
+ } else if (depthSpace == 0) {
pointer += heightSpace;
- else if (bool) {
+ } else if (bool) {
pointer += depthSpace;
bool = false;
} else {
diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java
index 9bc3b89ced9e..be98fde484fa 100644
--- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java
@@ -40,21 +40,29 @@ void isFull() {
buffer.put(generateInt());
assertFalse(buffer.isFull());
- for (int i = 1; i < BUFFER_SIZE; i++) buffer.put(generateInt());
+ for (int i = 1; i < BUFFER_SIZE; i++) {
+ buffer.put(generateInt());
+ }
assertTrue(buffer.isFull());
}
@Test
void get() {
assertNull(buffer.get());
- for (int i = 0; i < 100; i++) buffer.put(i);
- for (int i = 0; i < BUFFER_SIZE; i++) assertEquals(i, buffer.get());
+ for (int i = 0; i < 100; i++) {
+ buffer.put(i);
+ }
+ for (int i = 0; i < BUFFER_SIZE; i++) {
+ assertEquals(i, buffer.get());
+ }
assertNull(buffer.get());
}
@Test
void put() {
- for (int i = 0; i < BUFFER_SIZE; i++) assertTrue(buffer.put(generateInt()));
+ for (int i = 0; i < BUFFER_SIZE; i++) {
+ assertTrue(buffer.put(generateInt()));
+ }
assertFalse(buffer.put(generateInt()));
}
@@ -74,7 +82,9 @@ void concurrentTest() throws InterruptedException {
while (producerCountDownLatch.getCount() > 0) {
int count = (int) producerCountDownLatch.getCount();
boolean put = buffer.put(count);
- while (!put) put = buffer.put(count);
+ while (!put) {
+ put = buffer.put(count);
+ }
producerCountDownLatch.countDown();
}
});
@@ -85,7 +95,9 @@ void concurrentTest() throws InterruptedException {
while (consumerCountDownLatch.getCount() > 0) {
int count = (int) consumerCountDownLatch.getCount();
Integer item = buffer.get();
- while (item == null) item = buffer.get();
+ while (item == null) {
+ item = buffer.get();
+ }
resultAtomicArray.set(count - 1, item);
consumerCountDownLatch.countDown();
}
@@ -111,7 +123,9 @@ private int generateInt() {
private void shutDownExecutorSafely(ExecutorService executorService) {
try {
- if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) executorService.shutdownNow();
+ if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) {
+ executorService.shutdownNow();
+ }
} catch (InterruptedException e) {
executorService.shutdownNow();
}
@@ -120,7 +134,9 @@ private void shutDownExecutorSafely(ExecutorService executorService) {
public List getSortedListFrom(AtomicIntegerArray atomicArray) {
int length = atomicArray.length();
ArrayList result = new ArrayList<>(length);
- for (int i = 0; i < length; i++) result.add(atomicArray.get(i));
+ for (int i = 0; i < length; i++) {
+ result.add(atomicArray.get(i));
+ }
result.sort(Comparator.comparingInt(o -> o));
return result;
}
diff --git a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java
index faa0d0e952f9..7bebf13e9620 100644
--- a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java
@@ -8,7 +8,9 @@ class LinkedQueueTest {
@Test
public void testQue() {
LinkedQueue queue = new LinkedQueue<>();
- for (int i = 1; i < 5; i++) queue.enqueue(i);
+ for (int i = 1; i < 5; i++) {
+ queue.enqueue(i);
+ }
assertEquals(queue.peekRear(), 4);
assertEquals(queue.peek(2), 2);
@@ -20,7 +22,9 @@ public void testQue() {
// iterates over all the elements present
// as in the form of nodes
queue.forEach(integer -> {
- if (element[0]++ != integer) throw new AssertionError();
+ if (element[0]++ != integer) {
+ throw new AssertionError();
+ }
});
}
}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java
index e8294a323463..7daf8c6313cd 100644
--- a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java
@@ -49,12 +49,13 @@ void updateAndGet() {
int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr);
- for (int i = 0; i < 10; i++)
+ for (int i = 0; i < 10; i++) {
for (int j = i + 1; j < 10; j++) {
lazySegmentTree.updateRange(i, j, 1);
assertEquals(j - i, lazySegmentTree.getRange(i, j));
lazySegmentTree.updateRange(i, j, -1);
assertEquals(0, lazySegmentTree.getRange(i, j));
}
+ }
}
}
diff --git a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
index baccf319d15e..891c3066058e 100644
--- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
+++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
@@ -54,7 +54,9 @@ public void testMixes() throws IOException {
assertEquals(reader.read(), 'l'); // third letter
assertEquals(reader.peek(1), 'o'); // fourth letter
- for (int i = 0; i < 6; i++) reader.read();
+ for (int i = 0; i < 6; i++) {
+ reader.read();
+ }
try {
System.out.println((char) reader.peek(4));
} catch (Exception ignored) {
diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java
index 90910d511ca0..6307b8e19b5d 100644
--- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java
+++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java
@@ -117,7 +117,9 @@ public void testWithLargeValues() {
@Test
public void testWithLargeCountOfValues() {
var stream = new MedianOfRunningArrayInteger();
- for (int i = 1; i <= 1000; i++) stream.insert(i);
+ for (int i = 1; i <= 1000; i++) {
+ stream.insert(i);
+ }
assertEquals(500, stream.median());
}
From cdb3affdd9ac4b8c7ccf4c55b05f6914bb9e73d6 Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Fri, 14 Jun 2024 16:57:30 +0200
Subject: [PATCH 011/607] style: enable `AvoidNestedBlocks` in checkstyle
(#5228)
* enable style AvoidNestedBlocks
* refactor after enable style AvoidNestedBlocks
* fix clang
* fix checkstyle
* fix pmd
---------
Co-authored-by: Samuel Facchinello
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
checkstyle.xml | 2 +-
.../datastructures/hashmap/hashing/Main.java | 19 ++---
.../hashmap/hashing/MainCuckooHashing.java | 31 ++++---
.../com/thealgorithms/maths/MatrixUtil.java | 84 +------------------
.../java/com/thealgorithms/misc/Sort012D.java | 11 ++-
.../java/com/thealgorithms/sorts/DNFSort.java | 8 +-
.../thealgorithms/maths/MatrixUtilTest.java | 79 +++++++++++++++++
7 files changed, 117 insertions(+), 117 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/MatrixUtilTest.java
diff --git a/checkstyle.xml b/checkstyle.xml
index 48c8a4f1f377..45431b39897a 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -152,7 +152,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
index 082fd4b5ab2a..4d9b33b115c7 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
@@ -23,31 +23,30 @@ public static void main(String[] args) {
choice = scan.nextInt();
switch (choice) {
- case 1: {
+ case 1:
System.out.println("Enter the Key: ");
key = scan.nextInt();
h.insertHash(key);
break;
- }
- case 2: {
+
+ case 2:
System.out.println("Enter the Key delete: ");
key = scan.nextInt();
h.deleteHash(key);
break;
- }
- case 3: {
+
+ case 3:
System.out.println("Print table");
h.displayHashtable();
break;
- }
- case 4: {
+
+ case 4:
scan.close();
return;
- }
- default: {
+
+ default:
throw new IllegalArgumentException("Unexpected value: " + choice);
}
- }
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
index 5a4a56e9b37d..ff4c69a5ec78 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
@@ -27,45 +27,44 @@ public static void main(String[] args) {
choice = scan.nextInt();
switch (choice) {
- case 1: {
+ case 1:
System.out.println("Enter the Key: ");
key = scan.nextInt();
h.insertKey2HashTable(key);
break;
- }
- case 2: {
+
+ case 2:
System.out.println("Enter the Key delete: ");
key = scan.nextInt();
h.deleteKeyFromHashTable(key);
break;
- }
- case 3: {
+
+ case 3:
System.out.println("Print table:\n");
h.displayHashtable();
break;
- }
- case 4: {
+
+ case 4:
scan.close();
return;
- }
- case 5: {
+
+ case 5:
System.out.println("Enter the Key to find and print: ");
key = scan.nextInt();
System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n");
break;
- }
- case 6: {
+
+ case 6:
System.out.printf("Load factor is: %.2f%n", h.checkLoadFactor());
break;
- }
- case 7: {
+
+ case 7:
h.reHashTableIncreasesTableSize();
break;
- }
- default: {
+
+ default:
throw new IllegalArgumentException("Unexpected value: " + choice);
}
- }
}
}
}
diff --git a/src/main/java/com/thealgorithms/maths/MatrixUtil.java b/src/main/java/com/thealgorithms/maths/MatrixUtil.java
index 0759853d61a9..7e462f92e185 100644
--- a/src/main/java/com/thealgorithms/maths/MatrixUtil.java
+++ b/src/main/java/com/thealgorithms/maths/MatrixUtil.java
@@ -1,8 +1,6 @@
package com.thealgorithms.maths;
import java.math.BigDecimal;
-import java.util.Arrays;
-import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
@@ -15,19 +13,19 @@ public final class MatrixUtil {
private MatrixUtil() {
}
- public static boolean isValid(final BigDecimal[][] matrix) {
+ private static boolean isValid(final BigDecimal[][] matrix) {
return matrix != null && matrix.length > 0 && matrix[0].length > 0;
}
- public static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
+ private static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return (isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length && matrix1[0].length == matrix2[0].length);
}
- public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
+ private static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length);
}
- public static Optional operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction operation) {
+ private static Optional operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction operation) {
if (!hasEqualSizes(matrix1, matrix2)) {
return Optional.empty();
}
@@ -82,78 +80,4 @@ public static Optional multiply(final BigDecimal[][] matrix1, fi
return Optional.of(result);
}
-
- public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) {
- if (!Objects.deepEquals(actual, expected)) {
- throw new AssertionError(String.format("expected=%s but was actual=%s", Arrays.deepToString(expected), Arrays.deepToString(actual)));
- }
- }
-
- public static void main(final String[] args) {
- {
- final BigDecimal[][] matrix1 = {
- {new BigDecimal(3), new BigDecimal(2)},
- {new BigDecimal(0), new BigDecimal(1)},
- };
-
- final BigDecimal[][] matrix2 = {
- {new BigDecimal(1), new BigDecimal(3)},
- {new BigDecimal(2), new BigDecimal(0)},
- };
-
- final BigDecimal[][] actual = add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
-
- final BigDecimal[][] expected = {
- {new BigDecimal(4), new BigDecimal(5)},
- {new BigDecimal(2), new BigDecimal(1)},
- };
-
- assertThat(actual, expected);
- }
-
- {
- final BigDecimal[][] matrix1 = {
- {new BigDecimal(1), new BigDecimal(4)},
- {new BigDecimal(5), new BigDecimal(6)},
- };
-
- final BigDecimal[][] matrix2 = {
- {new BigDecimal(2), new BigDecimal(0)},
- {new BigDecimal(-2), new BigDecimal(-3)},
- };
-
- final BigDecimal[][] actual = subtract(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
-
- final BigDecimal[][] expected = {
- {new BigDecimal(-1), new BigDecimal(4)},
- {new BigDecimal(7), new BigDecimal(9)},
- };
-
- assertThat(actual, expected);
- }
-
- {
- final BigDecimal[][] matrix1 = {
- {new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)},
- {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)},
- {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)},
- };
-
- final BigDecimal[][] matrix2 = {
- {new BigDecimal(1), new BigDecimal(2)},
- {new BigDecimal(3), new BigDecimal(4)},
- {new BigDecimal(5), new BigDecimal(6)},
- };
-
- final BigDecimal[][] actual = multiply(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
-
- final BigDecimal[][] expected = {
- {new BigDecimal(22), new BigDecimal(28)},
- {new BigDecimal(49), new BigDecimal(64)},
- {new BigDecimal(76), new BigDecimal(100)},
- };
-
- assertThat(actual, expected);
- }
- }
}
diff --git a/src/main/java/com/thealgorithms/misc/Sort012D.java b/src/main/java/com/thealgorithms/misc/Sort012D.java
index febe13f4fec3..706e877e40c1 100644
--- a/src/main/java/com/thealgorithms/misc/Sort012D.java
+++ b/src/main/java/com/thealgorithms/misc/Sort012D.java
@@ -33,28 +33,27 @@ public static void sort012(int[] a) {
int temp;
while (mid <= h) {
switch (a[mid]) {
- case 0: {
+ case 0:
temp = a[l];
a[l] = a[mid];
a[mid] = temp;
l++;
mid++;
break;
- }
+
case 1:
mid++;
break;
- case 2: {
+ case 2:
temp = a[mid];
a[mid] = a[h];
a[h] = temp;
h--;
break;
- }
- default: {
+
+ default:
throw new IllegalArgumentException("Unexpected value: " + a[mid]);
}
- }
}
System.out.println("the Sorted array is ");
for (int i = 0; i < a.length; i++) {
diff --git a/src/main/java/com/thealgorithms/sorts/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java
index 50ba8c89715b..4b1e913cf3e0 100644
--- a/src/main/java/com/thealgorithms/sorts/DNFSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java
@@ -13,24 +13,24 @@ static void sort012(int[] a, int arrSize) {
int temp;
while (mid <= high) {
switch (a[mid]) {
- case 0: {
+ case 0:
temp = a[low];
a[low] = a[mid];
a[mid] = temp;
low++;
mid++;
break;
- }
+
case 1:
mid++;
break;
- case 2: {
+ case 2:
temp = a[mid];
a[mid] = a[high];
a[high] = temp;
high--;
break;
- }
+
default:
throw new IllegalArgumentException("Unexpected value: " + a[mid]);
}
diff --git a/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java b/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java
new file mode 100644
index 000000000000..f61ebe6a26cc
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java
@@ -0,0 +1,79 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.math.BigDecimal;
+import java.util.Objects;
+import org.junit.jupiter.api.Test;
+
+class MatrixUtilTest {
+
+ @Test
+ void add() {
+ final BigDecimal[][] matrix1 = {
+ {new BigDecimal(3), new BigDecimal(2)},
+ {BigDecimal.ZERO, BigDecimal.ONE},
+ };
+
+ final BigDecimal[][] matrix2 = {
+ {BigDecimal.ONE, new BigDecimal(3)},
+ {new BigDecimal(2), BigDecimal.ZERO},
+ };
+
+ final BigDecimal[][] actual = MatrixUtil.add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
+
+ final BigDecimal[][] expected = {
+ {new BigDecimal(4), new BigDecimal(5)},
+ {new BigDecimal(2), BigDecimal.ONE},
+ };
+
+ assertTrue(Objects.deepEquals(actual, expected));
+ }
+ @Test
+ void subtract() {
+ final BigDecimal[][] matrix1 = {
+ {BigDecimal.ONE, new BigDecimal(4)},
+ {new BigDecimal(5), new BigDecimal(6)},
+ };
+
+ final BigDecimal[][] matrix2 = {
+ {new BigDecimal(2), BigDecimal.ZERO},
+ {new BigDecimal(-2), new BigDecimal(-3)},
+ };
+
+ final BigDecimal[][] actual = MatrixUtil.subtract(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
+
+ final BigDecimal[][] expected = {
+ {new BigDecimal(-1), new BigDecimal(4)},
+ {new BigDecimal(7), new BigDecimal(9)},
+ };
+
+ assertTrue(Objects.deepEquals(actual, expected));
+ }
+
+ @Test
+ void multiply() {
+
+ final BigDecimal[][] matrix1 = {
+ {BigDecimal.ONE, new BigDecimal(2), new BigDecimal(3)},
+ {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)},
+ {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)},
+ };
+
+ final BigDecimal[][] matrix2 = {
+ {BigDecimal.ONE, new BigDecimal(2)},
+ {new BigDecimal(3), new BigDecimal(4)},
+ {new BigDecimal(5), new BigDecimal(6)},
+ };
+
+ final BigDecimal[][] actual = MatrixUtil.multiply(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
+
+ final BigDecimal[][] expected = {
+ {new BigDecimal(22), new BigDecimal(28)},
+ {new BigDecimal(49), new BigDecimal(64)},
+ {new BigDecimal(76), new BigDecimal(100)},
+ };
+
+ assertTrue(Objects.deepEquals(actual, expected));
+ }
+}
From c7ee0e73c2a04109daae88200fe17dfc3aa52bef Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Sat, 15 Jun 2024 11:02:09 +0200
Subject: [PATCH 012/607] Chore(deps): bump
org.apache.maven.plugins:maven-surefire-plugin from 3.2.5 to 3.3.0 (#5234)
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin
Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.2.5 to 3.3.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.2.5...surefire-3.3.0)
---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
dependency-type: direct:production
update-type: version-update:semver-minor
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index 98771e184caa..a3a2b39e24de 100644
--- a/pom.xml
+++ b/pom.xml
@@ -63,7 +63,7 @@
maven-surefire-plugin
- 3.2.5
+ 3.3.0
From 9973b8efc86cb31eb741e94646ca962528c1f17c Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Mon, 17 Jun 2024 22:55:20 +0200
Subject: [PATCH 013/607] refactor: redesign `StringMatchFiniteAutomata`
(#5222)
* refactor
* add test
* fix clang
* fix pmd
* remove main method
* refactor searchPattern with private class
* fix checkstyle
* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
* fix clang
* tests: add more test cases
---------
Co-authored-by: Samuel Facchinello
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.../others/StringMatchFiniteAutomata.java | 141 ++++++++++++------
.../others/StringMatchFiniteAutomataTest.java | 23 +++
2 files changed, 116 insertions(+), 48 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/others/StringMatchFiniteAutomataTest.java
diff --git a/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java b/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
index 22979e59b555..561845f41a07 100644
--- a/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
+++ b/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java
@@ -1,80 +1,125 @@
package com.thealgorithms.others;
+import java.util.Set;
+import java.util.TreeSet;
+
/**
- * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
+ * A class to perform string matching using finite automata.
+ *
+ * @author Prateek Kumar Oraon
*/
-import java.util.Scanner;
-
-// An implementation of string matching using finite automata
public final class StringMatchFiniteAutomata {
- private StringMatchFiniteAutomata() {
- }
-
- public static final int CHARS = 256;
- public static int[][] fa;
- public static Scanner scanner = null;
-
- 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 pat = scanner.nextLine();
- searchPat(text, pat);
+ // Constants
+ private static final int CHARS = Character.MAX_VALUE + 1; // Total number of characters in the input alphabet
- scanner.close();
+ // Private constructor to prevent instantiation
+ private StringMatchFiniteAutomata() {
}
- public static void searchPat(String text, String pat) {
- int m = pat.length();
- int n = text.length();
-
- fa = new int[m + 1][CHARS];
-
- computeFA(pat, m, fa);
-
- int state = 0;
- for (int i = 0; i < n; i++) {
- state = fa[state][text.charAt(i)];
-
- if (state == m) {
- System.out.println("Pattern found at index " + (i - m + 1));
+ /**
+ * Searches for the pattern in the given text using finite automata.
+ *
+ * @param text The text to search within.
+ * @param pattern The pattern to search for.
+ */
+ public static Set searchPattern(final String text, final String pattern) {
+ final var stateTransitionTable = computeStateTransitionTable(pattern);
+ FiniteAutomata finiteAutomata = new FiniteAutomata(stateTransitionTable);
+
+ Set indexFound = new TreeSet<>();
+ for (int i = 0; i < text.length(); i++) {
+ finiteAutomata.consume(text.charAt(i));
+
+ if (finiteAutomata.getState() == pattern.length()) {
+ indexFound.add(i - pattern.length() + 1);
}
}
+ return indexFound;
}
- // Computes finite automata for the pattern
- public static void computeFA(String pat, int m, int[][] fa) {
- for (int state = 0; state <= m; ++state) {
+ /**
+ * Computes the finite automata table for the given pattern.
+ *
+ * @param pattern The pattern to preprocess.
+ * @return The state transition table.
+ */
+ private static int[][] computeStateTransitionTable(final String pattern) {
+ final int patternLength = pattern.length();
+ int[][] stateTransitionTable = new int[patternLength + 1][CHARS];
+
+ for (int state = 0; state <= patternLength; ++state) {
for (int x = 0; x < CHARS; ++x) {
- fa[state][x] = getNextState(pat, m, state, x);
+ stateTransitionTable[state][x] = getNextState(pattern, patternLength, state, x);
}
}
+
+ return stateTransitionTable;
}
- public static int getNextState(String pat, int m, int state, int x) {
- // if current state is less than length of pattern
- // and input character of pattern matches the character in the alphabet
- // then automata goes to next state
- if (state < m && x == pat.charAt(state)) {
+ /**
+ * Gets the next state for the finite automata.
+ *
+ * @param pattern The pattern being matched.
+ * @param patternLength The length of the pattern.
+ * @param state The current state.
+ * @param x The current character from the input alphabet.
+ * @return The next state.
+ */
+ private static int getNextState(final String pattern, final int patternLength, final int state, final int x) {
+ // If the current state is less than the length of the pattern
+ // and the character matches the pattern character, go to the next state
+ if (state < patternLength && x == pattern.charAt(state)) {
return state + 1;
}
+ // Check for the highest prefix which is also a suffix
for (int ns = state; ns > 0; ns--) {
- if (pat.charAt(ns - 1) == x) {
+ if (pattern.charAt(ns - 1) == x) {
+ boolean match = true;
for (int i = 0; i < ns - 1; i++) {
- if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) {
+ if (pattern.charAt(i) != pattern.charAt(state - ns + i + 1)) {
+ match = false;
break;
}
-
- if (i == ns - 1) {
- return ns;
- }
+ }
+ if (match) {
+ return ns;
}
}
}
+ // If no prefix which is also a suffix is found, return 0
return 0;
}
+
+ /**
+ * A class representing the finite automata for pattern matching.
+ */
+ private static final class FiniteAutomata {
+ private int state = 0;
+ private final int[][] stateTransitionTable;
+
+ private FiniteAutomata(int[][] stateTransitionTable) {
+ this.stateTransitionTable = stateTransitionTable;
+ }
+
+ /**
+ * Consumes an input character and transitions to the next state.
+ *
+ * @param input The input character.
+ */
+ private void consume(final char input) {
+ state = stateTransitionTable[state][input];
+ }
+
+ /**
+ * Gets the current state of the finite automata.
+ *
+ * @return The current state.
+ */
+ private int getState() {
+ return state;
+ }
+ }
}
diff --git a/src/test/java/com/thealgorithms/others/StringMatchFiniteAutomataTest.java b/src/test/java/com/thealgorithms/others/StringMatchFiniteAutomataTest.java
new file mode 100644
index 000000000000..6e1947b76a38
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/StringMatchFiniteAutomataTest.java
@@ -0,0 +1,23 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Set;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+class StringMatchFiniteAutomataTest {
+
+ @ParameterizedTest
+ @MethodSource("provideTestCases")
+ void searchPattern(String text, String pattern, Set expectedOutput) {
+ assertEquals(expectedOutput, StringMatchFiniteAutomata.searchPattern(text, pattern));
+ }
+
+ private static Stream provideTestCases() {
+ return Stream.of(Arguments.of("abcbcabc", "abc", Set.of(0, 5)), Arguments.of("", "abc", Set.of()), Arguments.of("", "", Set.of()), Arguments.of("a", "b", Set.of()), Arguments.of("a", "a", Set.of(0)), Arguments.of("abcdabcabcabcd", "abcd", Set.of(0, 10)), Arguments.of("abc", "bcd", Set.of()),
+ Arguments.of("abcdefg", "xyz", Set.of()), Arguments.of("abcde", "", Set.of(1, 2, 3, 4, 5)), Arguments.of("abcabcabc", "abc", Set.of(0, 3, 6)), Arguments.of("abcabcabc", "abcabcabc", Set.of(0)), Arguments.of("aaabbbaaa", "aaa", Set.of(0, 6)), Arguments.of("abcdefg", "efg", Set.of(4)));
+ }
+}
From 39e065437c4c70d9d99c0de3343a980f423d5bc5 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Tue, 18 Jun 2024 08:40:46 +0200
Subject: [PATCH 014/607] Chore(deps): bump gitpod/workspace-java-21 from
2024-06-10-10-39-01 to 2024-06-17-10-03-09 (#5235)
Chore(deps): bump gitpod/workspace-java-21
Bumps gitpod/workspace-java-21 from 2024-06-10-10-39-01 to 2024-06-17-10-03-09.
---
updated-dependencies:
- dependency-name: gitpod/workspace-java-21
dependency-type: direct:production
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.gitpod.dockerfile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile
index 6ca2b97e8442..0718384d33ff 100644
--- a/.gitpod.dockerfile
+++ b/.gitpod.dockerfile
@@ -1,4 +1,4 @@
-FROM gitpod/workspace-java-21:2024-06-10-10-39-01
+FROM gitpod/workspace-java-21:2024-06-17-10-03-09
ENV LLVM_SCRIPT="tmp_llvm.sh"
From 74e51990c1f640a839f0fcc695d4faefce48d32f Mon Sep 17 00:00:00 2001
From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com>
Date: Tue, 18 Jun 2024 19:34:22 +0200
Subject: [PATCH 015/607] style: enable `InvalidJavadocPosition` in checkstyle
(#5237)
enable style InvalidJavadocPosition
Co-authored-by: Samuel Facchinello
---
checkstyle.xml | 2 +-
.../AllPathsFromSourceToTarget.java | 14 ++--
.../graphs/HamiltonianCycle.java | 18 ++---
.../datastructures/graphs/KahnsAlgorithm.java | 3 -
.../datastructures/graphs/Kosaraju.java | 71 ++++++++---------
.../graphs/TarjansAlgorithm.java | 79 +++++++++----------
.../datastructures/lists/RandomNode.java | 60 ++++++--------
.../lists/SinglyLinkedList.java | 9 +--
.../trees/CeilInBinarySearchTree.java | 2 -
.../datastructures/trees/TrieImp.java | 6 +-
.../dynamicprogramming/CatalanNumber.java | 9 +--
.../CountFriendsPairing.java | 18 ++---
.../dynamicprogramming/EditDistance.java | 3 +-
.../dynamicprogramming/KadaneAlgorithm.java | 24 +++---
.../dynamicprogramming/NewManShanksPrime.java | 13 ++-
.../dynamicprogramming/RegexMatching.java | 2 -
.../dynamicprogramming/SubsetCount.java | 6 +-
.../maths/AutomorphicNumber.java | 6 +-
.../com/thealgorithms/maths/DigitalRoot.java | 20 ++---
.../thealgorithms/maths/FastInverseSqrt.java | 45 +++++------
.../com/thealgorithms/maths/FrizzyNumber.java | 11 +--
.../thealgorithms/maths/JosephusProblem.java | 3 -
.../thealgorithms/maths/PascalTriangle.java | 6 +-
.../others/BankersAlgorithm.java | 4 +-
.../com/thealgorithms/others/Dijkstra.java | 9 +--
.../others/MemoryManagementAlgorithms.java | 4 +-
.../com/thealgorithms/others/RabinKarp.java | 9 ++-
.../others/RotateMatrixBy90Degrees.java | 3 +-
.../com/thealgorithms/sorts/LinkListSort.java | 33 ++++----
.../com/thealgorithms/strings/Anagrams.java | 36 ++++-----
.../NumbersDifferentSignsTest.java | 10 +--
.../graphs/BoruvkaAlgorithmTest.java | 6 +-
.../lists/QuickSortLinkedListTest.java | 10 +--
.../lists/ReverseKGroupTest.java | 10 +--
.../lists/RotateSinglyLinkedListsTest.java | 9 +--
.../PreemptivePrioritySchedulingTest.java | 9 +--
.../thealgorithms/strings/WordLadderTest.java | 38 ++++-----
37 files changed, 273 insertions(+), 347 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index 45431b39897a..af5e3527e32f 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -99,7 +99,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
index a21f8c05f292..6f93b704ffb2 100644
--- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -1,16 +1,14 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To find all possible paths from source to destination*/
-
-/**Wikipedia link -> https://en.wikipedia.org/wiki/Shortest_path_problem */
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.List;
+/**
+ * Program description - To find all possible paths from source to destination
+ * Wikipedia
+ *
+ * @author Siddhant Swarup Mallick
+ */
public class AllPathsFromSourceToTarget {
// No. of vertices in graph
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
index 65483eeeb65c..f12e3892b1b2 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -2,9 +2,9 @@
/**
* Java program for Hamiltonian Cycle
- * (https://en.wikipedia.org/wiki/Hamiltonian_path)
+ * wikipedia
*
- * @author Akshay Dubey (https://github.com/itsAkshayDubey)
+ * @author Akshay Dubey
*/
public class HamiltonianCycle {
@@ -58,31 +58,31 @@ public boolean isPathFound(int vertex) {
return true;
}
- /** all vertices selected but last vertex not linked to 0 **/
+ /* all vertices selected but last vertex not linked to 0 **/
if (this.pathCount == this.vertex) {
return false;
}
for (int v = 0; v < this.vertex; v++) {
- /** if connected **/
+ /* if connected **/
if (this.graph[vertex][v] == 1) {
- /** add to path **/
+ /* add to path **/
this.cycle[this.pathCount++] = v;
- /** remove connection **/
+ /* remove connection **/
this.graph[vertex][v] = 0;
this.graph[v][vertex] = 0;
- /** if vertex not already selected solve recursively **/
+ /* if vertex not already selected solve recursively **/
if (!isPresent(v)) {
return isPathFound(v);
}
- /** restore connection **/
+ /* restore connection **/
this.graph[vertex][v] = 1;
this.graph[v][vertex] = 1;
- /** remove path **/
+ /* remove path **/
this.cycle[--this.pathCount] = -1;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
index be83ea32f496..d5035cf625a6 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
@@ -8,9 +8,6 @@
import java.util.Queue;
import java.util.Set;
-/**
- * An algorithm that sorts a graph in toplogical order.
- */
/**
* A class that represents the adjaceny list of a graph
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
index 7c0c0b2bee78..c5f15839f997 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
@@ -6,53 +6,50 @@
/**
* Java program that implements Kosaraju Algorithm.
- * @author Shivanagouda S A (https://github.com/shivu2002a)
- *
- */
-
-/**
+ * @author Shivanagouda S A
+ *
* Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
- directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
- transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
- graph.
+directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
+transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
+graph.
* A graph is said to be strongly connected if every vertex is reachable from every other vertex.
- The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
- connected. Single node is always a SCC.
+The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
+connected. Single node is always a SCC.
* Example:
- 0 <--- 2 -------> 3 -------- > 4 ---- > 7
- | ^ | ^ ^
- | / | \ /
- | / | \ /
- v / v \ /
- 1 5 --> 6
+0 <--- 2 -------> 3 -------- > 4 ---- > 7
+| ^ | ^ ^
+| / | \ /
+| / | \ /
+v / v \ /
+1 5 --> 6
- For the above graph, the SCC list goes as follows:
- 0, 1, 2
- 3
- 4, 5, 6
- 7
+For the above graph, the SCC list goes as follows:
+0, 1, 2
+3
+4, 5, 6
+7
- We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
+We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
- {@summary}
+{@summary}
* Kosaraju Algorithm:
- 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
- sorted by lowest finish time.
- 2. Find the transpose graph by reversing the edges.
- 3. Pop nodes one by one from the stack and again to DFS on the modified graph.
-
- The transpose graph of the above graph:
- 0 ---> 2 <------- 3 <------- 4 <------ 7
- ^ / ^ \ /
- | / | \ /
- | / | \ /
- | v | v v
- 1 5 <--- 6
-
- We can observe that this graph has the same SCC as that of original graph.
+1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
+sorted by lowest finish time.
+2. Find the transpose graph by reversing the edges.
+3. Pop nodes one by one from the stack and again to DFS on the modified graph.
+
+The transpose graph of the above graph:
+0 ---> 2 <------- 3 <------- 4 <------ 7
+^ / ^ \ /
+| / | \ /
+| / | \ /
+| v | v v
+1 5 <--- 6
+
+We can observe that this graph has the same SCC as that of original graph.
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index 336e375f7d4e..de50044256c6 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -6,51 +6,48 @@
/**
* Java program that implements Tarjan's Algorithm.
- * @author Shivanagouda S A (https://github.com/shivu2002a)
- *
- */
-
-/**
+ * @author Shivanagouda S A
+ *
* Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a
- directed graph, which, from here onwards will be referred as SCC.
+directed graph, which, from here onwards will be referred as SCC.
* A graph is said to be strongly connected if every vertex is reachable from every other vertex.
- The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
- connected. Single node is always a SCC.
+The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
+connected. Single node is always a SCC.
* Example:
- 0 --------> 1 -------> 3 --------> 4
- ^ /
- | /
- | /
- | /
- | /
- | /
- | /
- | /
- | /
- | /
- |V
- 2
-
- For the above graph, the SCC list goes as follows:
- 1, 2, 0
- 3
- 4
-
- We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
-
- {@summary}
- Tarjan's Algorithm:
- * DFS search produces a DFS tree
- * Strongly Connected Components form subtrees of the DFS tree.
- * If we can find the head of these subtrees, we can get all the nodes in that subtree (including
- the head) and that will be one SCC.
- * There is no back edge from one SCC to another (here can be cross edges, but they will not be
- used).
-
- * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s
- algorithm does the same in a single DFS, which leads to much lower constant factors in the latter.
+0 --------> 1 -------> 3 --------> 4
+^ /
+| /
+| /
+| /
+| /
+| /
+| /
+| /
+| /
+| /
+|V
+2
+
+For the above graph, the SCC list goes as follows:
+1, 2, 0
+3
+4
+
+We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
+
+{@summary}
+Tarjan's Algorithm:
+ * DFS search produces a DFS tree
+ * Strongly Connected Components form subtrees of the DFS tree.
+ * If we can find the head of these subtrees, we can get all the nodes in that subtree (including
+the head) and that will be one SCC.
+ * There is no back edge from one SCC to another (here can be cross edges, but they will not be
+used).
+
+ * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s
+algorithm does the same in a single DFS, which leads to much lower constant factors in the latter.
*/
public class TarjansAlgorithm {
@@ -58,7 +55,7 @@ public class TarjansAlgorithm {
// Timer for tracking lowtime and insertion time
private int time;
- private List> sccList = new ArrayList>();
+ private final List> sccList = new ArrayList>();
public List> stronglyConnectedComponents(int v, List> graph) {
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
index 7318b8027f8c..dac88dd9f241 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
@@ -1,43 +1,37 @@
-/**
- * Author : Suraj Kumar
- * Github : https://github.com/skmodi649
- */
+package com.thealgorithms.datastructures.lists;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
/**
+ * @author Suraj Kumar
+ *
* PROBLEM DESCRIPTION :
* There is a single linked list and we are supposed to find a random node in the given linked list
- */
-
-/**
+ *
* ALGORITHM :
* Step 1 : START
* Step 2 : Create an arraylist of type integer
* Step 3 : Declare an integer type variable for size and linked list type for head
* Step 4 : We will use two methods, one for traversing through the linked list using while loop and
* also increase the size by 1
- *
+ *
* (a) RandomNode(head)
* (b) run a while loop till null;
* (c) add the value to arraylist;
* (d) increase the size;
- *
+ *
* Step 5 : Now use another method for getting random values using Math.random() and return the
* value present in arraylist for the calculated index Step 6 : Now in main() method we will simply
* insert nodes in the linked list and then call the appropriate method and then print the random
* node generated Step 7 : STOP
*/
-
-package com.thealgorithms.datastructures.lists;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
public class RandomNode {
- private List list;
+ private final List list;
private int size;
- private static Random rand = new Random();
+ private static final Random RAND = new Random();
static class ListNode {
@@ -63,10 +57,23 @@ public RandomNode(ListNode head) {
}
public int getRandom() {
- int index = rand.nextInt(size);
+ int index = RAND.nextInt(size);
return list.get(index);
}
+ /**
+ * OUTPUT :
+ * First output :
+ * Random Node : 25
+ * Second output :
+ * Random Node : 78
+ * Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ * Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ * Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ */
// Driver program to test above functions
public static void main(String[] args) {
ListNode head = new ListNode(15);
@@ -80,18 +87,3 @@ public static void main(String[] args) {
System.out.println("Random Node : " + randomNum);
}
}
-/**
- * OUTPUT :
- * First output :
- * Random Node : 25
- * Second output :
- * Random Node : 78
- * Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- * Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- */
-/**
- * Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- */
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index bca3c77f2724..d5d3f31f4b66 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -5,7 +5,7 @@
import java.util.StringJoiner;
/**
- * https://en.wikipedia.org/wiki/Linked_list
+ * wikipedia
*/
public class SinglyLinkedList implements Iterable {
@@ -95,7 +95,7 @@ public void swapNodes(int valueFirst, int valueSecond) {
previousB = currentB;
currentB = currentB.next;
}
- /** If either of 'a' or 'b' is not present, then return */
+ /* If either of 'a' or 'b' is not present, then return */
if (currentA == null || currentB == null) {
return;
}
@@ -334,11 +334,6 @@ public void insertNth(int data, int position) {
size++;
}
- /**
- * Swaps nodes of two given values a and b.
- *
- */
-
/**
* Deletes a node at the head
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
index f238b5e9fe8d..214e111b9f1a 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
@@ -18,8 +18,6 @@
*
* Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary
* search tree. Find ceil for 52 Answer: -1
- */
-/**
*
* Solution 1: Brute Force Solution: Do an inorder traversal and save result
* into an array. Iterate over the array to get an element equal to or greater
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
index 79c66cb90f01..d166653ff1b4 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
@@ -1,12 +1,12 @@
package com.thealgorithms.datastructures.trees;
+import java.util.Scanner;
+
/**
* Trie Data structure implementation without any libraries
*
- * @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
+ * @author Dheeraj Kumar Barnwal
*/
-import java.util.Scanner;
-
public class TrieImp {
public class TrieNode {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
index 8658bca3df52..d01066f611bd 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
@@ -1,15 +1,14 @@
package com.thealgorithms.dynamicprogramming;
+import java.util.Scanner;
/**
* This file contains an implementation of finding the nth CATALAN NUMBER using
- * dynamic programming Wikipedia: https://en.wikipedia.org/wiki/Catalan_number
+ * dynamic programming : Wikipedia
*
* Time Complexity: O(n^2) Space Complexity: O(n)
*
- * @author AMRITESH ANAND (https://github.com/amritesh19)
+ * @author AMRITESH ANAND
*/
-import java.util.Scanner;
-
public final class CatalanNumber {
private CatalanNumber() {
}
@@ -31,7 +30,7 @@ static long findNthCatalan(int n) {
catalanArray[0] = 1;
catalanArray[1] = 1;
- /**
+ /*
* The Catalan numbers satisfy the recurrence relation C₀=1 and Cn = Σ
* (Ci * Cn-1-i), i = 0 to n-1 , n > 0
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
index 8c70c9c3fada..e731524d4958 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
@@ -1,20 +1,14 @@
+package com.thealgorithms.dynamicprogramming;
+
/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-/**
+ * @author Siddhant Swarup Mallick
+
* In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal
* to number of times n appears in the sequence.
- */
-/**
- * Wikipedia Link - https://en.wikipedia.org/wiki/Golomb_sequence
+ * Wikipedia
+ * Program description - To find the Golomb sequence upto n
*/
-
-/** Program description - To find the Golomb sequence upto n */
-
-package com.thealgorithms.dynamicprogramming;
-
public final class CountFriendsPairing {
private CountFriendsPairing() {
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
index 6db30514db68..55ce50d30ea4 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
@@ -1,5 +1,6 @@
package com.thealgorithms.dynamicprogramming;
+import java.util.Scanner;
/**
* A DynamicProgramming based solution for Edit Distance problem In Java
* Description of Edit Distance with an Example:
@@ -22,8 +23,6 @@
*
* @author SUBHAM SANGHAI
*/
-import java.util.Scanner;
-
public final class EditDistance {
private EditDistance() {
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
index 9962cca217a0..905815d10a29 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
@@ -1,15 +1,20 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To find the maximum subarray sum */
package com.thealgorithms.dynamicprogramming;
+/**
+ * @author Siddhant Swarup Mallick
+ * Program description - To find the maximum subarray sum
+ */
public final class KadaneAlgorithm {
private KadaneAlgorithm() {
}
+ /**
+ * OUTPUT :
+ * Input - {89,56,98,123,26,75,12,40,39,68,91}
+ * Output: it returns either true or false
+ * 1st approach Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ */
public static boolean maxSum(int[] a, int predictedAnswer) {
int sum = a[0];
int runningSum = 0;
@@ -28,11 +33,4 @@ public static boolean maxSum(int[] a, int predictedAnswer) {
// It returns true if sum and predicted answer matches
// The predicted answer is the answer itself. So it always return true
}
- /**
- * OUTPUT :
- * Input - {89,56,98,123,26,75,12,40,39,68,91}
- * Output: it returns either true or false
- * 1st approach Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- */
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
index 5d31d40dacdc..d15ea1f78a78 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
@@ -1,13 +1,10 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To find the New Man Shanks Prime. */
-/** Wikipedia Link - https://en.wikipedia.org/wiki/Newman%E2%80%93Shanks%E2%80%93Williams_prime */
-
package com.thealgorithms.dynamicprogramming;
+/**
+ * @author Siddhant Swarup Mallick
+ * Program description - To find the New Man Shanks Prime.
+ * Wikipedia
+ */
public final class NewManShanksPrime {
private NewManShanksPrime() {
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
index 43427457e307..c07563ad0020 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
@@ -6,8 +6,6 @@
* cover the entire text ?-> matches single characters *-> match the sequence of
* characters
*
- */
-/**
* For calculation of Time and Space Complexity. Let N be length of src and M be
* length of pat
*
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
index cbe3ccae4ac7..0c5bc2c5884d 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
@@ -3,8 +3,8 @@
/**
* Find the number of subsets present in the given array with a sum equal to target.
* Based on Solution discussed on
- * StackOverflow(https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k)
- * @author Samrat Podder(https://github.com/samratpodder)
+ * StackOverflow
+ * @author Samrat Podder
*/
public final class SubsetCount {
private SubsetCount() {
@@ -19,7 +19,7 @@ private SubsetCount() {
*
*/
public static int getCount(int[] arr, int target) {
- /**
+ /*
* Base Cases - If target becomes zero, we have reached the required sum for the subset
* If we reach the end of the array arr then, either if target==arr[end], then we add one to
* the final count Otherwise we add 0 to the final count
diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
index 03c8a8989bb2..31f81da63f03 100644
--- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
+++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
@@ -1,15 +1,13 @@
package com.thealgorithms.maths;
+import java.math.BigInteger;
/**
- * Wikipedia link for Automorphic Number : https://en.wikipedia.org/wiki/Automorphic_number
+ * Automorphic Number
* A number is said to be an Automorphic, if it is present in the last digit(s)
* of its square. Example- Let the number be 25, its square is 625. Since,
* 25(The input number) is present in the last two digits of its square(625), it
* is an Automorphic Number.
*/
-
-import java.math.BigInteger;
-
public final class AutomorphicNumber {
private AutomorphicNumber() {
}
diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java
index 84b33f34c393..e8f5305c7569 100644
--- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java
+++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java
@@ -1,8 +1,7 @@
+package com.thealgorithms.maths;
+
/**
- * Author : Suraj Kumar Modi
- * https://github.com/skmodi649
- */
-/**
+ * @author Suraj Kumar Modi
* You are given a number n. You need to find the digital root of n.
* DigitalRoot of a number is the recursive sum of its digits until we get a single digit number.
*
@@ -20,8 +19,6 @@
* which is not a single digit number, hence
* sum of digit of 45 is 9 which is a single
* digit number.
- */
-/**
* Algorithm :
* Step 1 : Define a method digitalRoot(int n)
* Step 2 : Define another method single(int n)
@@ -38,8 +35,6 @@
* Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and
* print the result
*/
-package com.thealgorithms.maths;
-
final class DigitalRoot {
private DigitalRoot() {
}
@@ -53,6 +48,11 @@ public static int digitalRoot(int n) {
}
}
+ /**
+ * Time Complexity: O((Number of Digits)^2) Auxiliary Space Complexity:
+ * O(Number of Digits) Constraints: 1 <= n <= 10^7
+ */
+
// This function is used for finding the sum of the digits of number
public static int single(int n) {
if (n <= 9) { // if n becomes less than 10 than return n
@@ -63,7 +63,3 @@ public static int single(int n) {
} // n / 10 is the number obtained after removing the digit one by one
// The Sum of digits is stored in the Stack memory and then finally returned
}
-/**
- * Time Complexity: O((Number of Digits)^2) Auxiliary Space Complexity:
- * O(Number of Digits) Constraints: 1 <= n <= 10^7
- */
diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
index a0dbfb1f70a4..01a52b913d30 100644
--- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
+++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
@@ -1,18 +1,26 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To find out the inverse square root of the given number*/
-
-/** Wikipedia Link - https://en.wikipedia.org/wiki/Fast_inverse_square_root */
-
package com.thealgorithms.maths;
+/**
+ * @author Siddhant Swarup Mallick
+ * Program description - To find out the inverse square root of the given number
+ * Wikipedia
+ */
public final class FastInverseSqrt {
private FastInverseSqrt() {
}
-
+ /**
+ * Returns the inverse square root of the given number upto 6 - 8 decimal places.
+ * calculates the inverse square root of the given number and returns true if calculated answer
+ * matches with given answer else returns false
+ *
+ * OUTPUT :
+ * Input - number = 4522
+ * Output: it calculates the inverse squareroot of a number and returns true with it matches the
+ * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity :
+ * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns
+ * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1)
+ * Auxiliary Space Complexity : O(1)
+ */
public static boolean inverseSqrt(float number) {
float x = number;
float xhalf = 0.5f * x;
@@ -24,11 +32,10 @@ public static boolean inverseSqrt(float number) {
}
/**
- * Returns the inverse square root of the given number upto 6 - 8 decimal places.
+ * Returns the inverse square root of the given number upto 14 - 16 decimal places.
* calculates the inverse square root of the given number and returns true if calculated answer
* matches with given answer else returns false
*/
-
public static boolean inverseSqrt(double number) {
double x = number;
double xhalf = 0.5d * x;
@@ -41,18 +48,4 @@ public static boolean inverseSqrt(double number) {
x *= number;
return x == 1 / Math.sqrt(number);
}
- /**
- * Returns the inverse square root of the given number upto 14 - 16 decimal places.
- * calculates the inverse square root of the given number and returns true if calculated answer
- * matches with given answer else returns false
- */
}
-/**
- * OUTPUT :
- * Input - number = 4522
- * Output: it calculates the inverse squareroot of a number and returns true with it matches the
- * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity :
- * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns
- * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1)
- * Auxiliary Space Complexity : O(1)
- */
diff --git a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java
index 3ae5e021df1b..ff2b00c26ce2 100644
--- a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java
+++ b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java
@@ -1,12 +1,9 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To find the FrizzyNumber*/
-
package com.thealgorithms.maths;
+/**
+ * @author Siddhant Swarup Mallick
+ * Program description - To find the FrizzyNumber
+ */
public final class FrizzyNumber {
private FrizzyNumber() {
}
diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java
index 7d19623b3ed0..98d839011a7f 100644
--- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java
+++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java
@@ -5,9 +5,7 @@
* numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend
* brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings
* you to the 1st friend.
- */
-/**
The rules of the game are as follows:
1.Start at the 1st friend.
@@ -19,7 +17,6 @@
@author Kunal
*/
-
public final class JosephusProblem {
private JosephusProblem() {
}
diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java
index 95f92fbe1b49..9a9d4450cb98 100644
--- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java
+++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java
@@ -37,17 +37,17 @@ private PascalTriangle() {
*/
public static int[][] pascal(int n) {
- /**
+ /*
* @param arr An auxiliary array to store generated pascal triangle values
* @return
*/
int[][] arr = new int[n][n];
- /**
+ /*
* @param line Iterate through every line and print integer(s) in it
* @param i Represents the column number of the element we are currently on
*/
for (int line = 0; line < n; line++) {
- /**
+ /*
* @Every line has number of integers equal to line number
*/
for (int i = 0; i <= line; i++) {
diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
index a22d7c737415..836526529374 100644
--- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
@@ -1,5 +1,7 @@
package com.thealgorithms.others;
+import java.util.Scanner;
+
/**
* This file contains an implementation of BANKER'S ALGORITM Wikipedia:
* https://en.wikipedia.org/wiki/Banker%27s_algorithm
@@ -18,8 +20,6 @@
*
* @author AMRITESH ANAND (https://github.com/amritesh19)
*/
-import java.util.Scanner;
-
public final class BankersAlgorithm {
private BankersAlgorithm() {
}
diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java
index e2a778f8d6c3..a379100a2f3b 100644
--- a/src/main/java/com/thealgorithms/others/Dijkstra.java
+++ b/src/main/java/com/thealgorithms/others/Dijkstra.java
@@ -1,5 +1,9 @@
package com.thealgorithms.others;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NavigableSet;
+import java.util.TreeSet;
/**
* Dijkstra's algorithm,is a graph search algorithm that solves the
* single-source shortest path problem for a graph with nonnegative edge path
@@ -15,11 +19,6 @@
* https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of the
* comments are from RosettaCode.
*/
-import java.util.HashMap;
-import java.util.Map;
-import java.util.NavigableSet;
-import java.util.TreeSet;
-
public final class Dijkstra {
private Dijkstra() {
}
diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
index 1f5f455f24e3..0924b8569942 100644
--- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
+++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
@@ -1,11 +1,9 @@
package com.thealgorithms.others;
+import java.util.ArrayList;
/**
* @author Alexandros Lemonaris
*/
-
-import java.util.ArrayList;
-
public abstract class MemoryManagementAlgorithms {
/**
diff --git a/src/main/java/com/thealgorithms/others/RabinKarp.java b/src/main/java/com/thealgorithms/others/RabinKarp.java
index f8ca33becad3..cecf24e09b4a 100644
--- a/src/main/java/com/thealgorithms/others/RabinKarp.java
+++ b/src/main/java/com/thealgorithms/others/RabinKarp.java
@@ -1,12 +1,13 @@
package com.thealgorithms.others;
+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
*/
-import java.util.Scanner;
-
-// An implementation of Rabin-Karp string matching algorithm
-// Program will simply end if there is no match
public final class RabinKarp {
private RabinKarp() {
}
diff --git a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
index 3930ca3e95ff..6ad0ef024342 100644
--- a/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
+++ b/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java
@@ -1,11 +1,10 @@
package com.thealgorithms.others;
+import java.util.Scanner;
/**
* Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here
* is the algorithm for this problem .
*/
-import java.util.Scanner;
-
final class RotateMatrixBy90Degrees {
private RotateMatrixBy90Degrees() {
}
diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
index c9000f7e3778..bf8910d94eae 100644
--- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java
+++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
@@ -1,14 +1,10 @@
-/**
- * Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
-
-/** Program description - To sort the LinkList as per sorting technique */
-
package com.thealgorithms.sorts;
import java.util.Arrays;
-
+/**
+ * @author Siddhant Swarup Mallick
+ * Program description - To sort the LinkList as per sorting technique
+ */
public class LinkListSort {
public static boolean isSorted(int[] p, int option) {
@@ -116,17 +112,6 @@ public static boolean isSorted(int[] p, int option) {
// Switch case is used to call the classes as per the user requirement
return false;
}
-
- 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
- }
/**
* OUTPUT :
* Input - {89,56,98,123,26,75,12,40,39,68,91} is same for all the 3 classes
@@ -138,6 +123,16 @@ boolean compare(int[] a, int[] b) {
* 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 {
diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java
index 106be5e1a596..f5e8fa84cd41 100644
--- a/src/main/java/com/thealgorithms/strings/Anagrams.java
+++ b/src/main/java/com/thealgorithms/strings/Anagrams.java
@@ -12,8 +12,24 @@
*/
public class Anagrams {
- // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but
- // differ in running time.
+ /**
+ * 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but
+ * differ in running time.
+ * OUTPUT :
+ * first string ="deal" second string ="lead"
+ * Output: Anagram
+ * Input and output is constant for all four approaches
+ * 1st approach Time Complexity : O(n logn)
+ * Auxiliary Space Complexity : O(1)
+ * 2nd approach Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ * 3rd approach Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(1)
+ * 4th approach Time Complexity : O(n)
+ * Auxiliary Space Complexity : O(n)
+ * 5th approach Time Complexity: O(n)
+ * Auxiliary Space Complexity: O(1)
+ */
public static void main(String[] args) {
String first = "deal";
String second = "lead";
@@ -23,22 +39,6 @@ public static void main(String[] args) {
System.out.println(nm.approach1(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach3(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach4(first, second)); /* To activate methods for different approaches*/
- /**
- * OUTPUT :
- * first string ="deal" second string ="lead"
- * Output: Anagram
- * Input and output is constant for all four approaches
- * 1st approach Time Complexity : O(n logn)
- * Auxiliary Space Complexity : O(1)
- * 2nd approach Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- * 3rd approach Time Complexity : O(n)
- * Auxiliary Space Complexity : O(1)
- * 4th approach Time Complexity : O(n)
- * Auxiliary Space Complexity : O(n)
- * 5th approach Time Complexity: O(n)
- * Auxiliary Space Complexity: O(1)
- */
}
boolean approach1(String s, String t) {
diff --git a/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java
index 13761ac23e44..f54070d39cdd 100644
--- a/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java
+++ b/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java
@@ -1,15 +1,13 @@
package com.thealgorithms.bitmanipulation;
-/**
- * test Cases of Numbers Different Signs
- * @author Bama Charan Chhandogi
- */
-
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
-
+/**
+ * test Cases of Numbers Different Signs
+ * @author Bama Charan Chhandogi
+ */
class NumbersDifferentSignsTest {
@Test
diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java
index 579e236699b3..8cd0b0a6838f 100644
--- a/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java
@@ -30,7 +30,7 @@ public void testBoruvkaMSTV9E14() {
edges.add(new BoruvkaAlgorithm.Edge(7, 8, 11));
final var graph = new Graph(9, edges);
- /**
+ /*
* Adjacency matrix
* 0 1 2 3 4 5 6 7 8
* 0 0 10 12 0 0 0 0 0 0
@@ -56,7 +56,7 @@ void testBoruvkaMSTV2E1() {
final var graph = new Graph(2, edges);
- /**
+ /*
* Adjacency matrix
* 0 1
* 0 0 10
@@ -79,7 +79,7 @@ void testCompleteGraphK4() {
final var graph = new Graph(4, edges);
- /**
+ /*
* Adjacency matrix
* 0 1 2 3
* 0 0 7 2 5
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java
index c4113b787de9..91e2ba5d43ce 100644
--- a/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java
@@ -1,16 +1,14 @@
package com.thealgorithms.datastructures.lists;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import org.junit.jupiter.api.Test;
/**
* Test cases for QuickSortLinkedList
* Author: Prabhat-Kumar-42
* GitHub: https://github.com/Prabhat-Kumar-42
*/
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import org.junit.jupiter.api.Test;
-
public class QuickSortLinkedListTest {
@Test
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java
index c03f5b14c641..e7e3cca4083f 100644
--- a/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java
@@ -1,15 +1,13 @@
package com.thealgorithms.datastructures.lists;
-/**
- * Test cases for Reverse K Group LinkedList
- * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
- */
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
-
+/**
+ * Test cases for Reverse K Group LinkedList
+ * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ */
public class ReverseKGroupTest {
@Test
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java
index d3c020f8881b..8b2ae424364e 100644
--- a/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java
@@ -1,15 +1,14 @@
package com.thealgorithms.datastructures.lists;
-/**
- * Test cases for RotateSinglyLinkedLists
- * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
- */
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
+/**
+ * Test cases for RotateSinglyLinkedLists
+ * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ */
public class RotateSinglyLinkedListsTest {
@Test
diff --git a/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java
index 61e2a2ac2690..1c8a25dfda49 100644
--- a/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java
+++ b/src/test/java/com/thealgorithms/scheduling/PreemptivePrioritySchedulingTest.java
@@ -1,10 +1,5 @@
package com.thealgorithms.scheduling;
-/**
- * Test Cases of Preemptive Priority Scheduling Algorithm
- * @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
- */
-
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
@@ -12,6 +7,10 @@
import java.util.List;
import org.junit.jupiter.api.Test;
+/**
+ * Test Cases of Preemptive Priority Scheduling Algorithm
+ * @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
+ */
class PreemptivePrioritySchedulingTest {
@Test
diff --git a/src/test/java/com/thealgorithms/strings/WordLadderTest.java b/src/test/java/com/thealgorithms/strings/WordLadderTest.java
index 4f1d07ebdc4a..c59f2d8b31be 100644
--- a/src/test/java/com/thealgorithms/strings/WordLadderTest.java
+++ b/src/test/java/com/thealgorithms/strings/WordLadderTest.java
@@ -8,30 +8,32 @@
public class WordLadderTest {
+ /**
+ * Test 1:
+ * Input: beginWord = "hit", endWord = "cog", wordList =
+ * ["hot","dot","dog","lot","log","cog"]
+ * Output: 5
+ * Explanation: One shortest transformation sequence is
+ * "hit" -> "hot" -> "dot" -> "dog" -> cog"
+ * which is 5 words long.
+ */
@Test
public void testWordLadder() {
- /**
- * Test 1:
- * Input: beginWord = "hit", endWord = "cog", wordList =
- * ["hot","dot","dog","lot","log","cog"]
- * Output: 5
- * Explanation: One shortest transformation sequence is
- * "hit" -> "hot" -> "dot" -> "dog" -> cog"
- * which is 5 words long.
- */
-
List wordList1 = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog");
assertEquals(WordLadder.ladderLength("hit", "cog", wordList1), 5);
+ }
- /**
- * Test 2:
- * Input: beginWord = "hit", endWord = "cog", wordList =
- * ["hot","dot","dog","lot","log"]
- * Output: 0
- * Explanation: The endWord "cog" is not in wordList,
- * therefore there is no valid transformation sequence.
- */
+ /**
+ * Test 2:
+ * Input: beginWord = "hit", endWord = "cog", wordList =
+ * ["hot","dot","dog","lot","log"]
+ * Output: 0
+ * Explanation: The endWord "cog" is not in wordList,
+ * therefore there is no valid transformation sequence.
+ */
+ @Test
+ public void testWordLadder2() {
List wordList2 = Arrays.asList("hot", "dot", "dog", "lot", "log");
assertEquals(WordLadder.ladderLength("hit", "cog", wordList2), 0);
From bf4fc3f9c296c4510765f5bd8e885bed4c2f24dc Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Wed, 19 Jun 2024 07:18:53 +0200
Subject: [PATCH 016/607] Chore(deps): bump
org.apache.commons:commons-collections4 from 4.5.0-M1 to 4.5.0-M2 (#5240)
Chore(deps): bump org.apache.commons:commons-collections4
Bumps org.apache.commons:commons-collections4 from 4.5.0-M1 to 4.5.0-M2.
---
updated-dependencies:
- dependency-name: org.apache.commons:commons-collections4
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index a3a2b39e24de..6f28c62b5099 100644
--- a/pom.xml
+++ b/pom.xml
@@ -55,7 +55,7 @@
org.apache.commonscommons-collections4
- 4.5.0-M1
+ 4.5.0-M2
From a9db8428b29dc472c488191843af2110e115330c Mon Sep 17 00:00:00 2001
From: Alex K
Date: Wed, 19 Jun 2024 19:57:54 +0300
Subject: [PATCH 017/607] Refactoring BinaryInsertionSort according to common
SortAlgorithm approach (#5239)
* Refactoring BinaryInsertionSort according to common SortAlgorithm approach
* Formatting has been fixed
* Refactoring tests for BinaryInsertionSort according to SortingAlgorithmTest
* Removing redundant tests and improving variable readability
---------
Co-authored-by: alx
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.../sorts/BinaryInsertionSort.java | 21 +++++++++++----
.../sorts/BinaryInsertionSortTest.java | 27 ++++---------------
2 files changed, 21 insertions(+), 27 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java
index 13076c617c76..b6f5d92e7928 100644
--- a/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java
+++ b/src/main/java/com/thealgorithms/sorts/BinaryInsertionSort.java
@@ -1,17 +1,28 @@
package com.thealgorithms.sorts;
-public class BinaryInsertionSort {
+/**
+ * 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 {
- // Binary Insertion Sort method
- public int[] binaryInsertSort(int[] array) {
+ /**
+ * Sorts the given array using the Binary Insertion Sort algorithm.
+ *
+ * @param 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[] sort(T[] array) {
for (int i = 1; i < array.length; i++) {
- int temp = array[i];
+ final T temp = array[i];
int low = 0;
int high = i - 1;
while (low <= high) {
final int mid = (low + high) >>> 1;
- if (temp < array[mid]) {
+ if (temp.compareTo(array[mid]) < 0) {
high = mid - 1;
} else {
low = mid + 1;
diff --git a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
index bdd0702942a2..82cb3ba60987 100644
--- a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
+++ b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
@@ -1,27 +1,10 @@
package com.thealgorithms.sorts;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+class BinaryInsertionSortTest extends SortingAlgorithmTest {
+ private final BinaryInsertionSort binaryInsertionSort = new BinaryInsertionSort();
-import org.junit.jupiter.api.Test;
-
-class BinaryInsertionSortTest {
-
- BinaryInsertionSort bis = new BinaryInsertionSort();
-
- @Test
- // valid test case
- public void binaryInsertionSortTestNonDuplicate() {
- int[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7};
- int[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- int[] actResult = bis.binaryInsertSort(array);
- assertArrayEquals(expResult, actResult);
- }
-
- @Test
- public void binaryInsertionSortTestDuplicate() {
- int[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6};
- int[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9};
- int[] actResult = bis.binaryInsertSort(array);
- assertArrayEquals(expResult, actResult);
+ @Override
+ SortAlgorithm getSortAlgorithm() {
+ return binaryInsertionSort;
}
}
From 91101ec424d5ee78c5e132e29d6fb7492601c2ef Mon Sep 17 00:00:00 2001
From: Alex K
Date: Thu, 20 Jun 2024 09:26:09 +0300
Subject: [PATCH 018/607] Refactoring and code improving for OddEvenSort
(#5242)
* Refactoring and code improving for OddEvenSort, changing it according to SortAlgorithm approach, also applying SortUtils
* Fix checkstyle
* Remove redundant main, remove redundant tests.
---------
Co-authored-by: alx
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.../com/thealgorithms/sorts/OddEvenSort.java | 66 ++++++-------------
.../thealgorithms/sorts/OddEvenSortTest.java | 31 ++-------
2 files changed, 24 insertions(+), 73 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java
index fb6e4d2649cb..8db85f39e9ac 100644
--- a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java
+++ b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java
@@ -1,69 +1,41 @@
package com.thealgorithms.sorts;
-import java.util.Random;
-
-// https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
-public final class OddEvenSort {
- private OddEvenSort() {
- }
-
- public static void main(String[] args) {
- int[] arr = new int[100];
-
- Random random = new Random();
-
- // Print out unsorted elements
- for (int i = 0; i < arr.length; ++i) {
- arr[i] = random.nextInt(100) - 50;
- System.out.println(arr[i]);
- }
- System.out.println("--------------");
-
- oddEvenSort(arr);
-
- // Print Sorted elements
- for (int i = 0; i < arr.length - 1; ++i) {
- System.out.println(arr[i]);
- assert arr[i] <= arr[i + 1];
- }
- }
+/**
+ * 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 {
/**
- * Odd Even Sort algorithms implements
+ * Sorts the given array using the Odd-Even Sort algorithm.
*
- * @param arr the array contains elements
+ * @param the type of elements in the array, which must implement the Comparable interface
+ * @param arr the array to be sorted
+ * @return the sorted array
*/
- public static void oddEvenSort(int[] arr) {
+ @Override
+ public > T[] sort(T[] arr) {
boolean sorted = false;
while (!sorted) {
sorted = true;
for (int i = 1; i < arr.length - 1; i += 2) {
- if (arr[i] > arr[i + 1]) {
- swap(arr, i, i + 1);
+ if (arr[i].compareTo(arr[i + 1]) > 0) {
+ SortUtils.swap(arr, i, i + 1);
sorted = false;
}
}
for (int i = 0; i < arr.length - 1; i += 2) {
- if (arr[i] > arr[i + 1]) {
- swap(arr, i, i + 1);
+ if (arr[i].compareTo(arr[i + 1]) > 0) {
+ SortUtils.swap(arr, i, i + 1);
sorted = false;
}
}
}
- }
-
- /**
- * Helper function to swap two array values.
- *
- * @param arr the array contains elements
- * @param i the first index to be swapped
- * @param j the second index to be swapped
- */
- private static void swap(int[] arr, int i, int j) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
+ return arr;
}
}
diff --git a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java
index a7d0a58e229d..09ef8014cec1 100644
--- a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java
+++ b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java
@@ -1,36 +1,15 @@
package com.thealgorithms.sorts;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-
-import org.junit.jupiter.api.Test;
-
/**
* @author Tabbygray (https://github.com/Tabbygray)
* @see OddEvenSort
*/
-public class OddEvenSortTest {
- @Test
- public void oddEvenSortEmptyArray() {
- int[] inputArray = {};
- OddEvenSort.oddEvenSort(inputArray);
- int[] expectedOutput = {};
- assertArrayEquals(inputArray, expectedOutput);
- }
-
- @Test
- public void oddEvenSortNaturalNumberArray() {
- int[] inputArray = {18, 91, 86, 60, 21, 44, 37, 78, 98, 67};
- OddEvenSort.oddEvenSort(inputArray);
- int[] expectedOutput = {18, 21, 37, 44, 60, 67, 78, 86, 91, 98};
- assertArrayEquals(inputArray, expectedOutput);
- }
+public class OddEvenSortTest extends SortingAlgorithmTest {
+ private final OddEvenSort oddEvenSort = new OddEvenSort();
- @Test
- public void oddEvenSortIntegerArray() {
- int[] inputArray = {57, 69, -45, 12, -85, 3, -76, 36, 67, -14};
- OddEvenSort.oddEvenSort(inputArray);
- int[] expectedOutput = {-85, -76, -45, -14, 3, 12, 36, 57, 67, 69};
- assertArrayEquals(inputArray, expectedOutput);
+ @Override
+ SortAlgorithm getSortAlgorithm() {
+ return oddEvenSort;
}
}
From 15d2e706739451e0ca000bd63df82411d4d25053 Mon Sep 17 00:00:00 2001
From: Alex K
Date: Thu, 20 Jun 2024 18:47:43 +0300
Subject: [PATCH 019/607] Refactoring and code improving for StrandSort (#5243)
* Refactoring and code improving for StrandSort
* Fix java checkstyle
* Fix "Each variable declaration must be in its own statement"
* Fix "uses integer based for loops to iterate over a List"
---------
Co-authored-by: alx
---
.../com/thealgorithms/sorts/StrandSort.java | 83 +++++++++++++------
.../thealgorithms/sorts/StrandSortTest.java | 34 +-------
2 files changed, 62 insertions(+), 55 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java
index 51600812bbb1..58cd35628506 100644
--- a/src/main/java/com/thealgorithms/sorts/StrandSort.java
+++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java
@@ -1,46 +1,79 @@
package com.thealgorithms.sorts;
-import java.util.Iterator;
-import java.util.LinkedList;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
-public final class StrandSort {
- private StrandSort() {
+/**
+ * StrandSort class implementing the SortAlgorithm interface using arrays.
+ */
+public final class StrandSort implements SortAlgorithm {
+
+ /**
+ * Sorts the given array using the Strand Sort algorithm.
+ *
+ * @param The type of elements to be sorted, must be Comparable.
+ * @param unsorted The array to be sorted.
+ * @return The sorted array.
+ */
+ @Override
+ public > T[] sort(T[] unsorted) {
+ List unsortedList = new ArrayList<>(Arrays.asList(unsorted));
+ List sortedList = strandSort(unsortedList);
+ return sortedList.toArray(unsorted);
}
- // note: the input list is destroyed
- public static > LinkedList strandSort(LinkedList list) {
+ /**
+ * Strand Sort algorithm that sorts a list.
+ *
+ * @param The type of elements to be sorted, must be Comparable.
+ * @param list The list to be sorted.
+ * @return The sorted list.
+ */
+ private static > List strandSort(List list) {
if (list.size() <= 1) {
return list;
}
- LinkedList result = new LinkedList();
- while (list.size() > 0) {
- LinkedList sorted = new LinkedList();
- sorted.add(list.removeFirst()); // same as remove() or remove(0)
- for (Iterator it = list.iterator(); it.hasNext();) {
- E elem = it.next();
- if (sorted.peekLast().compareTo(elem) <= 0) {
- sorted.addLast(elem); // same as add(elem) or add(0, elem)
- it.remove();
+ List result = new ArrayList<>();
+ while (!list.isEmpty()) {
+ final List sorted = new ArrayList<>();
+ sorted.add(list.remove(0));
+ for (int i = 0; i < list.size();) {
+ if (sorted.get(sorted.size() - 1).compareTo(list.get(i)) <= 0) {
+ sorted.add(list.remove(i));
+ } else {
+ i++;
}
}
- result = merge(sorted, result);
+ result = merge(result, sorted);
}
return result;
}
- private static > LinkedList merge(LinkedList left, LinkedList right) {
- LinkedList result = new LinkedList();
- while (!left.isEmpty() && !right.isEmpty()) {
- // change the direction of this comparison to change the direction of the sort
- if (left.peek().compareTo(right.peek()) <= 0) {
- result.add(left.remove());
+ /**
+ * Merges two sorted lists into one sorted list.
+ *
+ * @param 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 > List merge(List left, List right) {
+ List 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.remove());
+ result.add(right.get(j));
+ j++;
}
}
- result.addAll(left);
- result.addAll(right);
+ result.addAll(left.subList(i, left.size()));
+ result.addAll(right.subList(j, right.size()));
return result;
}
}
diff --git a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java
index 91e85c81e5ec..a7250acf9bec 100644
--- a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java
+++ b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java
@@ -1,34 +1,8 @@
package com.thealgorithms.sorts;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
-
-import java.util.Arrays;
-import java.util.LinkedList;
-import org.junit.jupiter.api.Test;
-
-class StrandSortTest {
-
- @Test
- // valid test case
- public void strandSortNonDuplicateTest() {
- int[] expectedArray = {1, 2, 3, 4, 5};
- LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(3, 1, 2, 4, 5)));
- int[] actualArray = new int[actualList.size()];
- for (int i = 0; i < actualList.size(); i++) {
- actualArray[i] = actualList.get(i);
- }
- assertArrayEquals(expectedArray, actualArray);
- }
-
- @Test
- // valid test case
- public void strandSortDuplicateTest() {
- int[] expectedArray = {2, 2, 2, 5, 7};
- LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(7, 2, 2, 2, 5)));
- int[] actualArray = new int[actualList.size()];
- for (int i = 0; i < actualList.size(); i++) {
- actualArray[i] = actualList.get(i);
- }
- assertArrayEquals(expectedArray, actualArray);
+class StrandSortTest extends SortingAlgorithmTest {
+ @Override
+ SortAlgorithm getSortAlgorithm() {
+ return new StrandSort();
}
}
From 8ef69bc85404a714c186f8aead26cd3d92595610 Mon Sep 17 00:00:00 2001
From: Alex Klymenko
Date: Fri, 21 Jun 2024 22:37:58 +0300
Subject: [PATCH 020/607] Improving BitonicSort (#5244)
* Improving BitonicSort
* Moving max method to SortingUtils
* Adding Javadoc to merge method
* Fix for test and code improvements
* Improving code readability
* Renaming method parameters
---------
Co-authored-by: alx
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
---
.../com/thealgorithms/sorts/BitonicSort.java | 149 +++++++++++-------
.../thealgorithms/sorts/BitonicSortTest.java | 8 +
2 files changed, 99 insertions(+), 58 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/sorts/BitonicSortTest.java
diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java
index b4b26299562f..90d204818729 100644
--- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java
+++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java
@@ -1,79 +1,112 @@
package com.thealgorithms.sorts;
-/* Java program for Bitonic Sort. Note that this program
-works only when size of input is a power of 2. */
-public class BitonicSort {
-
- /* The parameter dir indicates the sorting direction,
- ASCENDING or DESCENDING; if (a[i] > a[j]) agrees
- with the direction, then a[i] and a[j] are
- interchanged. */
- void compAndSwap(int[] a, int i, int j, int dir) {
- if ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) {
- // Swapping elements
- int temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
+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,
}
- /* It recursively sorts a bitonic sequence in ascending
- order, if dir = 1, and in descending order otherwise
- (means dir=0). The sequence to be sorted starts at
- index position low, the parameter cnt is the number
- of elements to be sorted.*/
- void bitonicMerge(int[] a, int low, int cnt, int dir) {
- if (cnt > 1) {
- int k = cnt / 2;
- for (int i = low; i < low + k; i++) {
- compAndSwap(a, i, i + k, dir);
- }
- bitonicMerge(a, low, k, dir);
- bitonicMerge(a, low + k, k, dir);
+ /**
+ * Sorts the given array using the Bitonic Sort algorithm.
+ *
+ * @param 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[] 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);
}
- /* This funcion first produces a bitonic sequence by
- recursively sorting its two halves in opposite sorting
- orders, and then calls bitonicMerge to make them in
- the same order */
- void bitonicSort(int[] a, int low, int cnt, int dir) {
+ private > void bitonicSort(final T[] array, final int low, final int cnt, final Direction direction) {
if (cnt > 1) {
- int k = cnt / 2;
+ final int k = cnt / 2;
- // sort in ascending order since dir here is 1
- bitonicSort(a, low, k, 1);
+ // Sort first half in ascending order
+ bitonicSort(array, low, k, Direction.ASCENDING);
- // sort in descending order since dir here is 0
- bitonicSort(a, low + k, k, 0);
+ // Sort second half in descending order
+ bitonicSort(array, low + k, cnt - k, Direction.DESCENDING);
- // Will merge whole sequence in ascending order
- // since dir=1.
- bitonicMerge(a, low, cnt, dir);
+ // Merge the whole sequence in ascending order
+ bitonicMerge(array, low, cnt, direction);
}
}
- /*Caller of bitonicSort for sorting the entire array
- of length N in ASCENDING order */
- void sort(int[] a, int n, int up) {
- bitonicSort(a, 0, n, up);
+ /**
+ * Merges the bitonic sequence in the specified direction.
+ *
+ * @param 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 > void bitonicMerge(T[] array, int low, int cnt, Direction direction) {
+ if (cnt > 1) {
+ final int k = cnt / 2;
+
+ final BiPredicate areSorted = (direction == Direction.ASCENDING) ? (a, b) -> a.compareTo(b) < 0 : (a, b) -> a.compareTo(b) > 0;
+ 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);
+ }
}
- /* A utility function to print array of size n */
- static void printArray(int[] arr) {
- int n = arr.length;
- for (int i = 0; i < n; ++i) {
- System.out.print(arr[i] + " ");
+ /**
+ * 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;
}
- System.out.println();
+
+ return 1 << count;
}
- public static void main(String[] args) {
- int[] a = {3, 7, 4, 8, 6, 2, 1, 5};
- int up = 1;
- BitonicSort ob = new BitonicSort();
- ob.sort(a, a.length, up);
- System.out.println("\nSorted array");
- printArray(a);
+ /**
+ * Finds the maximum element in the given array.
+ *
+ * @param 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 max(final T[] array) {
+ return Arrays.stream(array).max(Comparable::compareTo).orElseThrow();
}
}
diff --git a/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java b/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java
new file mode 100644
index 000000000000..60c4bbe9d342
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java
@@ -0,0 +1,8 @@
+package com.thealgorithms.sorts;
+
+public class BitonicSortTest extends SortingAlgorithmTest {
+ @Override
+ SortAlgorithm getSortAlgorithm() {
+ return new BitonicSort();
+ }
+}
From e8f1990c8cf815bba8b3329a549759f060c01496 Mon Sep 17 00:00:00 2001
From: Alex Klymenko
Date: Sat, 22 Jun 2024 11:18:39 +0300
Subject: [PATCH 021/607] Replace the various swap method variants with
SortUtils.swap (#5245)
Fix different variants of swap methods to SortUtils.swap
Co-authored-by: AlexKlm
---
.../sorts/DualPivotQuickSort.java | 18 ++++++------------
.../com/thealgorithms/sorts/ExchangeSort.java | 8 +-------
.../thealgorithms/sorts/IntrospectiveSort.java | 16 +++++-----------
.../com/thealgorithms/sorts/SelectionSort.java | 4 +---
.../com/thealgorithms/sorts/SimpleSort.java | 4 +---
.../java/com/thealgorithms/sorts/SlowSort.java | 4 +---
.../java/com/thealgorithms/sorts/SwapSort.java | 4 +---
7 files changed, 16 insertions(+), 42 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
index 5a6ba256521f..b02168f627c3 100644
--- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
@@ -45,7 +45,7 @@ private static > void dualPivotQuicksort(T[] array, int
*/
private static > int[] partition(T[] array, int left, int right) {
if (array[left].compareTo(array[right]) > 0) {
- swap(array, left, right);
+ SortUtils.swap(array, left, right);
}
T pivot1 = array[left];
@@ -58,7 +58,7 @@ private static > int[] partition(T[] array, int left, in
while (less <= great) {
// If element is less than pivot1
if (array[less].compareTo(pivot1) < 0) {
- swap(array, less, left++);
+ SortUtils.swap(array, less, left++);
}
// If element is greater or equal to pivot2
@@ -67,10 +67,10 @@ else if (array[less].compareTo(pivot2) >= 0) {
great--;
}
- swap(array, less, great--);
+ SortUtils.swap(array, less, great--);
if (array[less].compareTo(pivot1) < 0) {
- swap(array, less, left++);
+ SortUtils.swap(array, less, left++);
}
}
@@ -79,19 +79,13 @@ else if (array[less].compareTo(pivot2) >= 0) {
j--;
great++;
// Bring the pivots to their appropriate positions
- swap(array, left, j);
- swap(array, right, great);
+ SortUtils.swap(array, left, j);
+ SortUtils.swap(array, right, great);
// return the pivots' indices
return new int[] {less, great};
}
- private static > void swap(T[] array, int left, int right) {
- T temp = array[left];
- array[left] = array[right];
- array[right] = temp;
- }
-
/**
* Main method
*
diff --git a/src/main/java/com/thealgorithms/sorts/ExchangeSort.java b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java
index 28303430950c..67e94b889671 100644
--- a/src/main/java/com/thealgorithms/sorts/ExchangeSort.java
+++ b/src/main/java/com/thealgorithms/sorts/ExchangeSort.java
@@ -32,16 +32,10 @@ public > T[] sort(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i].compareTo(array[j]) > 0) {
- swap(array, i, j);
+ SortUtils.swap(array, i, j);
}
}
}
return array;
}
-
- private void swap(T[] array, int i, int j) {
- T temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- }
}
diff --git a/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java b/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java
index 930bb02c7ce7..32d942dc78db 100644
--- a/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java
+++ b/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java
@@ -16,12 +16,6 @@ public > T[] sort(T[] a) {
return a;
}
- private static > void swap(T[] a, int i, int j) {
- T temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
-
private static > void introSort(T[] a, int low, int high, int depth) {
while (high - low > INSERTION_SORT_THRESHOLD) {
if (depth == 0) {
@@ -37,16 +31,16 @@ private static > void introSort(T[] a, int low, int high
private static > int partition(T[] a, int low, int high) {
int pivotIndex = low + (int) (Math.random() * (high - low + 1));
- swap(a, pivotIndex, high);
+ SortUtils.swap(a, pivotIndex, high);
T pivot = a[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (a[j].compareTo(pivot) <= 0) {
i++;
- swap(a, i, j);
+ SortUtils.swap(a, i, j);
}
}
- swap(a, i + 1, high);
+ SortUtils.swap(a, i + 1, high);
return i + 1;
}
@@ -67,7 +61,7 @@ private static > void heapSort(T[] a, int low, int high)
heapify(a, i, high - low + 1, low);
}
for (int i = high; i > low; i--) {
- swap(a, low, i);
+ SortUtils.swap(a, low, i);
heapify(a, low, i - low, low);
}
}
@@ -83,7 +77,7 @@ private static > void heapify(T[] a, int i, int n, int l
largest = right;
}
if (largest != i) {
- swap(a, i, largest);
+ SortUtils.swap(a, i, largest);
heapify(a, largest, n, low);
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java
index e43df7fe622e..cc7b3cc6b662 100644
--- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java
@@ -1,7 +1,5 @@
package com.thealgorithms.sorts;
-import static com.thealgorithms.sorts.SortUtils.swap;
-
public class SelectionSort implements SortAlgorithm {
/**
@@ -22,7 +20,7 @@ public > T[] sort(T[] arr) {
}
}
if (minIndex != i) {
- swap(arr, i, minIndex);
+ SortUtils.swap(arr, i, minIndex);
}
}
return arr;
diff --git a/src/main/java/com/thealgorithms/sorts/SimpleSort.java b/src/main/java/com/thealgorithms/sorts/SimpleSort.java
index 7aab7c784b92..110bc6e4c5b7 100644
--- a/src/main/java/com/thealgorithms/sorts/SimpleSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SimpleSort.java
@@ -9,9 +9,7 @@ public > T[] sort(T[] array) {
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (SortUtils.less(array[j], array[i])) {
- T element = array[j];
- array[j] = array[i];
- array[i] = element;
+ SortUtils.swap(array, i, j);
}
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/SlowSort.java b/src/main/java/com/thealgorithms/sorts/SlowSort.java
index dcd426b31c0d..38a5fa458778 100644
--- a/src/main/java/com/thealgorithms/sorts/SlowSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SlowSort.java
@@ -20,9 +20,7 @@ private > void sort(T[] array, int i, int j) {
sort(array, i, m);
sort(array, m + 1, j);
if (SortUtils.less(array[j], array[m])) {
- T temp = array[j];
- array[j] = array[m];
- array[m] = temp;
+ SortUtils.swap(array, j, m);
}
sort(array, i, j - 1);
}
diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java
index 08ce988578f3..e0fa7087a49e 100644
--- a/src/main/java/com/thealgorithms/sorts/SwapSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java
@@ -18,9 +18,7 @@ public > T[] sort(T[] array) {
int amountSmallerElements = this.getSmallerElementCount(array, index);
if (amountSmallerElements > 0 && index != amountSmallerElements) {
- T element = array[index];
- array[index] = array[amountSmallerElements];
- array[amountSmallerElements] = element;
+ SortUtils.swap(array, index, amountSmallerElements);
} else {
index++;
}
From 308bdcfc192768c57071130181db30a1d387d0df Mon Sep 17 00:00:00 2001
From: Alex Klymenko
Date: Sat, 22 Jun 2024 23:29:17 +0300
Subject: [PATCH 022/607] Refactor: Replace Swap and Comparison Methods with
SortUtils Utility Methods (#5246)
* Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods
* Rename parameter unsorted to array
---------
Co-authored-by: Alex Klymenko
---
.../com/thealgorithms/sorts/HeapSort.java | 41 ++++++++-----------
1 file changed, 16 insertions(+), 25 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/HeapSort.java b/src/main/java/com/thealgorithms/sorts/HeapSort.java
index eec705ba476a..91d556b17b16 100644
--- a/src/main/java/com/thealgorithms/sorts/HeapSort.java
+++ b/src/main/java/com/thealgorithms/sorts/HeapSort.java
@@ -9,48 +9,39 @@ public class HeapSort implements SortAlgorithm {
/**
* For simplicity, we are considering the heap root index as 1 instead of 0.
- * It simplifies future calculations. Because of that we are decreasing the
- * provided indexes by 1 in {@link #swap(Object[], int, int)} and
- * {@link #less(Comparable[], int, int)} functions.
+ * 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[] sort(T[] unsorted) {
- int n = unsorted.length;
- heapify(unsorted, n);
+ public > T[] sort(T[] array) {
+ int n = array.length;
+ heapify(array, n);
while (n > 1) {
- swap(unsorted, 1, n--);
- siftDown(unsorted, 1, n);
+ SortUtils.swap(array, 0, n - 1);
+ n--;
+ siftDown(array, 1, n);
}
- return unsorted;
+ return array;
}
- private static > void heapify(T[] unsorted, int n) {
+ private static > void heapify(T[] array, int n) {
for (int k = n / 2; k >= 1; k--) {
- siftDown(unsorted, k, n);
+ siftDown(array, k, n);
}
}
- private static > void siftDown(T[] unsorted, int k, int n) {
+ private static > void siftDown(T[] array, int k, int n) {
while (2 * k <= n) {
int j = 2 * k;
- if (j < n && less(unsorted, j, j + 1)) {
+ if (j < n && SortUtils.less(array[j - 1], array[j])) {
j++;
}
- if (!less(unsorted, k, j)) {
+ if (!SortUtils.less(array[k - 1], array[j - 1])) {
break;
}
- swap(unsorted, k, j);
+ SortUtils.swap(array, k - 1, j - 1);
k = j;
}
}
-
- private static void swap(T[] array, int idx, int idy) {
- T swap = array[idx - 1];
- array[idx - 1] = array[idy - 1];
- array[idy - 1] = swap;
- }
-
- private static > boolean less(T[] array, int idx, int idy) {
- return array[idx - 1].compareTo(array[idy - 1]) < 0;
- }
}
From a5b4c6173f711ddc6a73350d9db2deca625ed762 Mon Sep 17 00:00:00 2001
From: Alex Klymenko
Date: Mon, 24 Jun 2024 09:49:01 +0300
Subject: [PATCH 023/607] fix: avoid infinite loop in `SwapSort` (#5248)
---------
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
---
.../com/thealgorithms/sorts/SwapSort.java | 38 ++-----------------
.../com/thealgorithms/sorts/SwapSortTest.java | 8 ++++
2 files changed, 11 insertions(+), 35 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/sorts/SwapSortTest.java
diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java
index e0fa7087a49e..fe3597c0e2b4 100644
--- a/src/main/java/com/thealgorithms/sorts/SwapSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java
@@ -17,8 +17,8 @@ public > T[] sort(T[] array) {
while (index < len - 1) {
int amountSmallerElements = this.getSmallerElementCount(array, index);
- if (amountSmallerElements > 0 && index != amountSmallerElements) {
- SortUtils.swap(array, index, amountSmallerElements);
+ if (amountSmallerElements > 0) {
+ SortUtils.swap(array, index, index + amountSmallerElements);
} else {
index++;
}
@@ -29,7 +29,7 @@ public > T[] sort(T[] array) {
private > int getSmallerElementCount(T[] array, int index) {
int counter = 0;
- for (int i = 0; i < array.length; i++) {
+ for (int i = index + 1; i < array.length; i++) {
if (SortUtils.less(array[i], array[index])) {
counter++;
}
@@ -37,36 +37,4 @@ private > int getSmallerElementCount(T[] array, int inde
return counter;
}
-
- public static void main(String[] args) {
- // ==== Int =======
- Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9};
- System.out.print("unsorted: ");
- SortUtils.print(a);
- System.out.println();
-
- new SwapSort().sort(a);
- System.out.print("sorted: ");
- SortUtils.print(a);
- System.out.println();
-
- // ==== String =======
- String[] b = {
- "banana",
- "berry",
- "orange",
- "grape",
- "peach",
- "cherry",
- "apple",
- "pineapple",
- };
- System.out.print("unsorted: ");
- SortUtils.print(b);
- System.out.println();
-
- new SwapSort().sort(b);
- System.out.print("sorted: ");
- SortUtils.print(b);
- }
}
diff --git a/src/test/java/com/thealgorithms/sorts/SwapSortTest.java b/src/test/java/com/thealgorithms/sorts/SwapSortTest.java
new file mode 100644
index 000000000000..c1638a385940
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/SwapSortTest.java
@@ -0,0 +1,8 @@
+package com.thealgorithms.sorts;
+
+public class SwapSortTest extends SortingAlgorithmTest {
+ @Override
+ SortAlgorithm getSortAlgorithm() {
+ return new SwapSort();
+ }
+}
From 7b17ead902395e1494df9686ea6d128767956ea4 Mon Sep 17 00:00:00 2001
From: abdala-elgendy <111305293+abdala-elgendy@users.noreply.github.com>
Date: Mon, 24 Jun 2024 11:42:29 +0300
Subject: [PATCH 024/607] chore: improve FibonacciHeap (#5251)
---
.../thealgorithms/datastructures/heaps/FibonacciHeap.java | 8 ++++----
.../com/thealgorithms/datastructures/heaps/MaxHeap.java | 2 +-
.../com/thealgorithms/datastructures/heaps/MinHeap.java | 2 +-
.../datastructures/heaps/MinPriorityQueue.java | 6 +++---
4 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
index 4734483b518b..d248bc3316ed 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -8,7 +8,7 @@ public class FibonacciHeap {
private static int totalCuts = 0;
private int numOfTrees = 0;
private int numOfHeapNodes = 0;
- private int markedHeapNoodesCounter = 0;
+ private int markedHeapNodesCounter = 0;
/*
* a constructor for an empty Heap
@@ -190,7 +190,7 @@ private void decreaseKey(HeapNode x, int delta) {
* Potential = #trees + 2*#markedNodes
*/
public int potential() {
- return numOfTrees + (2 * markedHeapNoodesCounter);
+ return numOfTrees + (2 * markedHeapNodesCounter);
}
/**
@@ -232,7 +232,7 @@ private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion
curr.mark();
if (!curr.isRoot()) {
- this.markedHeapNoodesCounter++;
+ this.markedHeapNodesCounter++;
}
} else {
if (curr.isRoot()) {
@@ -252,7 +252,7 @@ private void cascadingCuts(HeapNode curr) {
private void cut(HeapNode curr) {
curr.parent.rank--;
if (curr.marked) {
- this.markedHeapNoodesCounter--;
+ this.markedHeapNodesCounter--;
curr.marked = false;
}
if (curr.parent.child == curr) { // we should change the parent's child
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
index 067aae738914..9010aae4cae5 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
@@ -22,7 +22,7 @@ public MaxHeap(List listElements) {
System.out.println("Null element. Not added to heap");
}
}
- if (maxHeap.size() == 0) {
+ if (maxHeap.isEmpty()) {
System.out.println("No element has been added, empty heap.");
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
index 6e972205acfe..46864fba0047 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
@@ -22,7 +22,7 @@ public MinHeap(List listElements) {
System.out.println("Null element. Not added to heap");
}
}
- if (minHeap.size() == 0) {
+ if (minHeap.isEmpty()) {
System.out.println("No element has been added, empty heap.");
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
index 2ad4ed5320c9..9d19e9aaee1a 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
@@ -14,11 +14,11 @@
*/
public class MinPriorityQueue {
- private int[] heap;
- private int capacity;
+ private final int[] heap;
+ private final int capacity;
private int size;
- // calss the constructor and initializes the capacity
+ // class the constructor and initializes the capacity
MinPriorityQueue(int c) {
this.capacity = c;
this.size = 0;
From 22f2abd94f81582a547c9352c136b27c22db08d7 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Mon, 24 Jun 2024 10:47:33 +0200
Subject: [PATCH 025/607] style: enable `WhitespaceAround` in checktyle (#5241)
---
checkstyle.xml | 2 +-
.../java/com/thealgorithms/dynamicprogramming/UniquePaths.java | 3 ++-
src/test/java/com/thealgorithms/maths/MeansTest.java | 2 +-
3 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index af5e3527e32f..4fc237d29c5a 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -143,7 +143,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
index c48bdea2dc8d..80b553f2744c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
@@ -19,7 +19,8 @@
public final class UniquePaths {
- private UniquePaths(){};
+ private UniquePaths() {
+ }
/**
* Calculates the number of unique paths using a 1D dynamic programming array.
diff --git a/src/test/java/com/thealgorithms/maths/MeansTest.java b/src/test/java/com/thealgorithms/maths/MeansTest.java
index a1c07e25bea3..bb2b4b6d1c50 100644
--- a/src/test/java/com/thealgorithms/maths/MeansTest.java
+++ b/src/test/java/com/thealgorithms/maths/MeansTest.java
@@ -59,7 +59,7 @@ void arithmeticMeanMultipleNumbers() {
@Test
void geometricMeanMultipleNumbers() {
- LinkedList numbers = new LinkedList<>() {};
+ LinkedList numbers = new LinkedList<>();
numbers.addAll(Lists.newArrayList(1d, 2d, 3d, 4d, 5d, 6d, 1.25));
assertEquals(2.6426195539300585, Means.geometric(numbers));
}
From a710fe11c47bdfb80342f851c189d167035b7b1c Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Mon, 24 Jun 2024 10:49:50 +0200
Subject: [PATCH 026/607] style: include `SPP_USE_ISEMPTY` (#5238)
---
spotbugs-exclude.xml | 3 ---
.../com/thealgorithms/devutils/nodes/LargeTreeNode.java | 2 +-
src/main/java/com/thealgorithms/searches/QuickSelect.java | 2 +-
.../java/com/thealgorithms/sorts/MergeSortRecursive.java | 6 +++---
4 files changed, 5 insertions(+), 8 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 0a5354382a4f..9a9712e0a571 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -132,9 +132,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
index 1575e3649bc3..95d53ecb1f7a 100644
--- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
+++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
@@ -64,7 +64,7 @@ public LargeTreeNode(E data, LargeTreeNode parentNode, Collection> getChildNodes() {
diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java
index c89abb00e9da..d5f695293a6a 100644
--- a/src/main/java/com/thealgorithms/searches/QuickSelect.java
+++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java
@@ -31,7 +31,7 @@ private QuickSelect() {
public static > T select(List list, int n) {
Objects.requireNonNull(list, "The list of elements must not be null.");
- if (list.size() == 0) {
+ if (list.isEmpty()) {
String msg = "The list of elements must not be empty.";
throw new IllegalArgumentException(msg);
}
diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
index f67ba631be0e..910157b83231 100644
--- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
+++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
@@ -34,13 +34,13 @@ private static List merge(List arr) {
}
private static List sort(List unsortedA, List unsortedB) {
- if (unsortedA.size() <= 0 && unsortedB.size() <= 0) {
+ if (unsortedA.isEmpty() && unsortedB.isEmpty()) {
return new ArrayList<>();
}
- if (unsortedA.size() <= 0) {
+ if (unsortedA.isEmpty()) {
return unsortedB;
}
- if (unsortedB.size() <= 0) {
+ if (unsortedB.isEmpty()) {
return unsortedA;
}
if (unsortedA.get(0) <= unsortedB.get(0)) {
From d36f54bd396789ec7b95350285ce5d1b5c7c0972 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Tue, 25 Jun 2024 07:07:07 +0200
Subject: [PATCH 027/607] style: include `NM_CLASS_NAMING_CONVENTION` and
`NM_METHOD_NAMING_CONVENTION` (#5231)
---
spotbugs-exclude.xml | 6 ------
1 file changed, 6 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 9a9712e0a571..111b41720fbb 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -17,9 +17,6 @@
-
-
-
@@ -44,9 +41,6 @@
-
-
-
From cff3a59530f759fa98423983711c54021f0bbe45 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Tue, 25 Jun 2024 08:51:24 +0200
Subject: [PATCH 028/607] style: include `BED_BOGUS_EXCEPTION_DECLARATION`
(#5233)
---
spotbugs-exclude.xml | 3 ---
.../java/com/thealgorithms/stacks/DuplicateBrackets.java | 8 --------
2 files changed, 11 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 111b41720fbb..f1b48d52829b 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -114,9 +114,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java b/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
index 2fb03de77de5..482bda0a02a2 100644
--- a/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
+++ b/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
@@ -8,7 +8,6 @@
// e.g.'
// ((a + b) + (c + d)) -> false
// (a + b) + ((c + d)) -> true
-import java.util.Scanner;
import java.util.Stack;
public final class DuplicateBrackets {
@@ -36,11 +35,4 @@ public static boolean check(String str) {
}
return false;
}
-
- public static void main(String[] args) throws Exception {
- Scanner sc = new Scanner(System.in);
- String str = sc.nextLine();
- System.out.println(check(str));
- sc.close();
- }
}
From f279f9d589febf61b52bb61caf89d02230e65324 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Tue, 25 Jun 2024 07:01:32 +0000
Subject: [PATCH 029/607] Chore(deps): bump gitpod/workspace-java-21 from
2024-06-17-10-03-09 to 2024-06-24-08-46-07 (#5253)
Dependabot couldn't find the original pull request head commit, a1d54164dac1d97b56d75099b00f7db58bf8fb48.
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.gitpod.dockerfile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile
index 0718384d33ff..31b013937b4e 100644
--- a/.gitpod.dockerfile
+++ b/.gitpod.dockerfile
@@ -1,4 +1,4 @@
-FROM gitpod/workspace-java-21:2024-06-17-10-03-09
+FROM gitpod/workspace-java-21:2024-06-24-08-46-07
ENV LLVM_SCRIPT="tmp_llvm.sh"
From 971f5fc85bd7d80c83c4cf7da5854029cd30bf91 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Wed, 26 Jun 2024 08:48:20 +0200
Subject: [PATCH 030/607] Chore(deps): bump
com.github.spotbugs:spotbugs-maven-plugin from 4.8.5.0 to 4.8.6.0 (#5256)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin
Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.5.0 to 4.8.6.0.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.5.0...spotbugs-maven-plugin-4.8.6.0)
---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
dependency-type: direct:production
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index 6f28c62b5099..67d16dfccca2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -125,7 +125,7 @@
com.github.spotbugsspotbugs-maven-plugin
- 4.8.5.0
+ 4.8.6.0spotbugs-exclude.xmltrue
From 7054535d36a14e4fa17ef7f236f710ab7b9f8b4b Mon Sep 17 00:00:00 2001
From: Alex Klymenko
Date: Wed, 26 Jun 2024 23:41:54 +0300
Subject: [PATCH 031/607] feat: add `WaveSort` (#5252)
* Implementing WaveSort Algorithm
* Refactor: Tests to ParameterizedTest
* Checkstyle: Fix wrong align
* Checkstyle: Fix wrong align for second line
* Checkstyle: Remove redundant line
* Naming: fix method name
* Documentation: adding links
* Fix: adding test for isWaveSorted method
* Documentation: adding description for WaveSort
* Testing: test wave sort assert
* Checkstyle: remove redundant whitespace
* Checkstyle: remove redundant newline
* Testing: improving tests
---------
Co-authored-by: alxklm
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
---
DIRECTORY.md | 2 +
.../com/thealgorithms/sorts/WaveSort.java | 46 ++++++++++++++++++
.../com/thealgorithms/sorts/WaveSortTest.java | 48 +++++++++++++++++++
3 files changed, 96 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/sorts/WaveSort.java
create mode 100644 src/test/java/com/thealgorithms/sorts/WaveSortTest.java
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 7c46336f0911..c4eb2a6d30aa 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -528,6 +528,7 @@
* [TopologicalSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/TopologicalSort.java)
* [TreeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/TreeSort.java)
* [WiggleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/WiggleSort.java)
+ * [WaveSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/WaveSort.java)
* stacks
* [BalancedBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java)
* [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java)
@@ -885,6 +886,7 @@
* [TopologicalSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java)
* [TreeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TreeSortTest.java)
* [WiggleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java)
+ * [WaveSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WaveSortTest.java)
* stacks
* [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
* strings
diff --git a/src/main/java/com/thealgorithms/sorts/WaveSort.java b/src/main/java/com/thealgorithms/sorts/WaveSort.java
new file mode 100644
index 000000000000..31aad52c6b4a
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/WaveSort.java
@@ -0,0 +1,46 @@
+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 The type of elements in the array, which must be Comparable.
+ * @return The sorted array.
+ */
+ @Override
+ public > 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 The type of elements in the array, which must be Comparable.
+ * @return true if the array is wave sorted, false otherwise.
+ */
+ public > 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;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/sorts/WaveSortTest.java b/src/test/java/com/thealgorithms/sorts/WaveSortTest.java
new file mode 100644
index 000000000000..3bc6fa63c01d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/WaveSortTest.java
@@ -0,0 +1,48 @@
+package com.thealgorithms.sorts;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class WaveSortTest {
+ @ParameterizedTest
+ @MethodSource("arraysToWaveSort")
+ public void waveSortTest(Integer[] array) {
+ WaveSort waveSort = new WaveSort();
+ final var inputHistogram = getHistogram(array);
+ final var sortedArray = waveSort.sort(array);
+ assertTrue(waveSort.isWaveSorted(sortedArray));
+ final var sortedHistogram = getHistogram(sortedArray);
+ assertEquals(inputHistogram, sortedHistogram, "Element counts do not match");
+ }
+
+ private Map getHistogram(Integer[] array) {
+ Map histogram = new HashMap<>();
+ for (final var element : array) {
+ histogram.put(element, histogram.getOrDefault(element, 0) + 1);
+ }
+ return histogram;
+ }
+
+ private static Stream