style: format code (#4212)

close #4204
This commit is contained in:
acbin
2023-06-09 18:52:05 +08:00
committed by GitHub
parent ad03086f54
commit 00282efd8b
521 changed files with 5233 additions and 7309 deletions

View File

@ -41,12 +41,7 @@ class BinarySearch implements SearchAlgorithm {
* @param right The upper bound
* @return the location of the key
*/
private <T extends Comparable<T>> int search(
T[] array,
T key,
int left,
int right
) {
private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) {
if (right < left) {
return -1; // this means that the key not found
}
@ -71,12 +66,11 @@ class BinarySearch implements SearchAlgorithm {
int size = 100;
int maxElement = 100000;
Integer[] integers = IntStream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[]::new);
Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[] ::new);
// The element that should be found
int shouldBeFound = integers[r.nextInt(size - 1)];
@ -84,15 +78,11 @@ class BinarySearch implements SearchAlgorithm {
BinarySearch search = new BinarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}

View File

@ -1,11 +1,12 @@
package com.thealgorithms.searches;
/*
To apply this method, the provided array must be strictly sorted. In this method, two pointers, one at 0th row
& the other at the last row are taken & the searching is done on the basis of the middle element of the middle column.
If that element is equal to target, its coordinates are returned, else if it is smaller than the target, the rows above
that element are ignored (because the elements above it will also be smaller than the target), else that element is
greater than the target, then the rows below it are ignored.
To apply this method, the provided array must be strictly sorted. In this method, two pointers, one
at 0th row & the other at the last row are taken & the searching is done on the basis of the middle
element of the middle column. If that element is equal to target, its coordinates are returned, else
if it is smaller than the target, the rows above that element are ignored (because the elements
above it will also be smaller than the target), else that element is greater than the target, then
the rows below it are ignored.
*/
public class BinarySearch2dArray {
@ -19,69 +20,55 @@ public class BinarySearch2dArray {
int startRow = 0, endRow = rowCount - 1, midCol = colCount / 2;
while (startRow < endRow - 1) {
int midRow = startRow + (endRow - startRow) / 2; //getting the index of middle row
int midRow = startRow + (endRow - startRow) / 2; // getting the index of middle row
if (arr[midRow][midCol] == target) {
return new int[] { midRow, midCol };
} else if (arr[midRow][midCol] < target) startRow =
midRow; else endRow = midRow;
return new int[] {midRow, midCol};
} else if (arr[midRow][midCol] < target)
startRow = midRow;
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 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) return new int[] {
startRow,
midCol,
};
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]) return binarySearch(
arr,
target,
endRow,
0,
midCol - 1
); else return binarySearch(
arr,
target,
endRow,
midCol + 1,
colCount - 1
);
if (target <= arr[endRow][midCol - 1])
return binarySearch(arr, target, endRow, 0, midCol - 1);
else
return binarySearch(arr, target, endRow, midCol + 1, colCount - 1);
}
static int[] binarySearch(
int[][] arr,
int target,
int row,
int colStart,
int colEnd
) {
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) return new int[] {
row,
midIndex,
}; else if (arr[row][midIndex] < target) colStart =
midIndex + 1; else colEnd = midIndex - 1;
if (arr[row][midIndex] == target)
return new int[] {
row,
midIndex,
};
else if (arr[row][midIndex] < target)
colStart = midIndex + 1;
else
colEnd = midIndex - 1;
}
return new int[] { -1, -1 };
return new int[] {-1, -1};
}
}

View File

@ -40,8 +40,7 @@ public class DepthFirstSearch {
return Optional.of(node);
}
return node
.getSubNodes()
return node.getSubNodes()
.stream()
.map(value -> search(value, name))
.flatMap(Optional::stream)
@ -51,32 +50,22 @@ public class DepthFirstSearch {
public static void assertThat(final Object actual, final Object expected) {
if (!Objects.equals(actual, expected)) {
throw new AssertionError(
String.format("expected=%s but was actual=%s", expected, actual)
);
String.format("expected=%s but was actual=%s", expected, actual));
}
}
public static void main(final String[] args) {
final Node rootNode = new Node(
"A",
final Node rootNode = new Node("A",
List.of(
new Node(
"B",
List.of(
new Node("D"),
new Node("F", List.of(new Node("H"), new Node("I")))
)
),
new Node("C", List.of(new Node("G"))),
new Node("E")
)
);
new Node("B",
List.of(new Node("D"), new Node("F", List.of(new Node("H"), new Node("I"))))),
new Node("C", List.of(new Node("G"))), new Node("E")));
{
final String expected = "I";
final Node result = search(rootNode, expected)
.orElseThrow(() -> new AssertionError("Node not found!"));
.orElseThrow(() -> new AssertionError("Node not found!"));
assertThat(result.getName(), expected);
}
@ -85,7 +74,7 @@ public class DepthFirstSearch {
final String expected = "G";
final Node result = search(rootNode, expected)
.orElseThrow(() -> new AssertionError("Node not found!"));
.orElseThrow(() -> new AssertionError("Node not found!"));
assertThat(result.getName(), expected);
}
@ -94,7 +83,7 @@ public class DepthFirstSearch {
final String expected = "E";
final Node result = search(rootNode, expected)
.orElseThrow(() -> new AssertionError("Node not found!"));
.orElseThrow(() -> new AssertionError("Node not found!"));
assertThat(result.getName(), expected);
}

View File

@ -14,12 +14,11 @@ class ExponentialSearch implements SearchAlgorithm {
int size = 100;
int maxElement = 100000;
Integer[] integers = IntStream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[]::new);
Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[] ::new);
// The element that should be found
int shouldBeFound = integers[r.nextInt(size - 1)];
@ -27,16 +26,12 @@ class ExponentialSearch implements SearchAlgorithm {
ExponentialSearch search = new ExponentialSearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
@Override
@ -54,11 +49,6 @@ class ExponentialSearch implements SearchAlgorithm {
range = range * 2;
}
return Arrays.binarySearch(
array,
range / 2,
Math.min(range, array.length),
key
);
return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key);
}
}

View File

@ -59,22 +59,14 @@ public class FibonacciSearch implements SearchAlgorithm {
// Driver Program
public static void main(String[] args) {
Integer[] integers = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
int size = integers.length;
Integer shouldBeFound = 128;
FibonacciSearch fsearch = new FibonacciSearch();
int atIndex = fsearch.find(integers, shouldBeFound);
System.out.println(
"Should be found: " +
shouldBeFound +
". Found " +
integers[atIndex] +
" at index " +
atIndex +
". An array length " +
size
);
System.out.println("Should be found: " + shouldBeFound + ". Found " + integers[atIndex]
+ " at index " + atIndex + ". An array length " + size);
}
}

View File

@ -3,8 +3,8 @@ package com.thealgorithms.searches;
import java.util.*;
/*
Problem Statement:
Given an array, find out how many times it has to been rotated
Problem Statement:
Given an array, find out how many times it has to been rotated
from its initial sorted position.
Input-Output:
Eg. [11,12,15,18,2,5,6,8]
@ -12,14 +12,16 @@ import java.util.*;
(One rotation means putting the first element to the end)
Note: The array cannot contain duplicates
Logic:
Logic:
The position of the minimum element will give the number of times the array has been rotated
from its initial sorted position.
Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on.
Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N).
If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]<a[i+1].
Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations
[6,8,11,12,15,18,2,5] and so on. Finding the minimum element will take O(N) time but, we can use
Binary Search to find the mimimum element, we can reduce the complexity to O(log N). If we look
at the rotated array, to identify the minimum element (say a[i]), we observe that
a[i-1]>a[i]<a[i+1].
Some other test cases:
Some other test cases:
1. [1,2,3,4] Number of rotations: 0 or 4(Both valid)
2. [15,17,2,3,5] Number of rotations: 3
*/
@ -33,9 +35,7 @@ class HowManyTimesRotated {
a[i] = sc.nextInt();
}
System.out.println(
"The array has been rotated " + rotated(a) + " times"
);
System.out.println("The array has been rotated " + rotated(a) + " times");
sc.close();
}

View File

@ -30,12 +30,8 @@ class InterpolationSearch {
while (start <= end && key >= array[start] && key <= array[end]) {
// Probing the position with keeping
// uniform distribution in mind.
int pos =
start +
(
((end - start) / (array[end] - array[start])) *
(key - array[start])
);
int pos
= start + (((end - start) / (array[end] - array[start])) * (key - array[start]));
// Condition of target found
if (array[pos] == key) {
@ -58,11 +54,8 @@ class InterpolationSearch {
Random r = new Random();
int size = 100;
int maxElement = 100000;
int[] integers = IntStream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray();
int[] integers
= IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray();
// the element that should be found
int shouldBeFound = integers[r.nextInt(size - 1)];
@ -70,15 +63,11 @@ class InterpolationSearch {
InterpolationSearch search = new InterpolationSearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}

View File

@ -58,11 +58,10 @@ public final class IterativeBinarySearch implements SearchAlgorithm {
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[]::new);
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[] ::new);
// the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
@ -70,15 +69,11 @@ public final class IterativeBinarySearch implements SearchAlgorithm {
IterativeBinarySearch search = new IterativeBinarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}

View File

@ -56,11 +56,10 @@ public class IterativeTernarySearch implements SearchAlgorithm {
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[]::new);
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[] ::new);
// the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
@ -68,15 +67,11 @@ public class IterativeTernarySearch implements SearchAlgorithm {
IterativeTernarySearch search = new IterativeTernarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}

View File

@ -6,7 +6,7 @@ public class JumpSearch implements SearchAlgorithm {
public static void main(String[] args) {
JumpSearch jumpSearch = new JumpSearch();
Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < array.length; i++) {
assert jumpSearch.find(array, i) == i;
}

View File

@ -22,7 +22,8 @@ class KMPSearch {
i++;
}
if (j == M) {
System.out.println("Found pattern " + "at index " + (i - j));
System.out.println("Found pattern "
+ "at index " + (i - j));
int index = (i - j);
j = lps[j - 1];
return index;
@ -31,7 +32,10 @@ class KMPSearch {
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) j = lps[j - 1]; else i = i + 1;
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
System.out.println("No pattern found");

View File

@ -42,10 +42,8 @@ public class LinearSearch implements SearchAlgorithm {
Random r = new Random();
int size = 200;
int maxElement = 100;
Integer[] integers = Stream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.toArray(Integer[]::new);
Integer[] integers
= Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[] ::new);
// the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
@ -53,12 +51,7 @@ public class LinearSearch implements SearchAlgorithm {
LinearSearch search = new LinearSearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
}
}

View File

@ -29,9 +29,9 @@ public class LinearSearchThread {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {}
boolean found =
t.getResult() || t1.getResult() || t2.getResult() || t3.getResult();
} catch (InterruptedException e) {
}
boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult();
System.out.println("Found = " + found);
}
}

View File

@ -33,12 +33,11 @@ class LowerBound implements SearchAlgorithm {
int size = 100;
int maxElement = 100000;
Integer[] integers = IntStream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[]::new);
Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[] ::new);
// The element for which the lower bound is to be found
int val = integers[r.nextInt(size - 1)] + 1;
@ -46,16 +45,12 @@ class LowerBound implements SearchAlgorithm {
LowerBound search = new LowerBound();
int atIndex = search.find(integers, val);
System.out.printf(
"Val: %d. Lower Bound Found %d at index %d. An array length %d%n",
val,
integers[atIndex],
atIndex,
size
);
System.out.printf("Val: %d. Lower Bound Found %d at index %d. An array length %d%n", val,
integers[atIndex], atIndex, size);
boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val;
System.out.printf("Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
System.out.printf(
"Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
}
/**
@ -78,12 +73,7 @@ class LowerBound implements SearchAlgorithm {
* @param right The upper bound
* @return the location of the key
*/
private <T extends Comparable<T>> int search(
T[] array,
T key,
int left,
int right
) {
private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) {
if (right <= left) {
return left;
}

View File

@ -23,7 +23,8 @@ public class MonteCarloTreeSearch {
int score;
int visitCount;
public Node() {}
public Node() {
}
public Node(Node parent, boolean isPlayersTurn) {
this.parent = parent;
@ -78,9 +79,7 @@ public class MonteCarloTreeSearch {
winnerNode = getWinnerNode(rootNode);
printScores(rootNode);
System.out.format(
"\nThe optimal node is: %02d\n",
rootNode.childNodes.indexOf(winnerNode) + 1
);
"\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1);
return winnerNode;
}
@ -120,13 +119,10 @@ public class MonteCarloTreeSearch {
break;
}
uctTemp =
((double) childNode.score / childNode.visitCount) +
1.41 *
Math.sqrt(
Math.log(promisingNode.visitCount) /
(double) childNode.visitCount
);
uctTemp = ((double) childNode.score / childNode.visitCount)
+ 1.41
* Math.sqrt(
Math.log(promisingNode.visitCount) / (double) childNode.visitCount);
if (uctTemp > uctIndex) {
uctIndex = uctTemp;
@ -165,10 +161,8 @@ public class MonteCarloTreeSearch {
tempNode.visitCount++;
// Add wining scores to bouth player and opponent depending on the turn.
if (
(tempNode.isPlayersTurn && isPlayerWinner) ||
(!tempNode.isPlayersTurn && !isPlayerWinner)
) {
if ((tempNode.isPlayersTurn && isPlayerWinner)
|| (!tempNode.isPlayersTurn && !isPlayerWinner)) {
tempNode.score += WIN_SCORE;
}
@ -177,22 +171,15 @@ public class MonteCarloTreeSearch {
}
public Node getWinnerNode(Node rootNode) {
return Collections.max(
rootNode.childNodes,
Comparator.comparing(c -> c.score)
);
return Collections.max(rootNode.childNodes, Comparator.comparing(c -> c.score));
}
public void printScores(Node rootNode) {
System.out.println("N.\tScore\t\tVisits");
for (int i = 0; i < rootNode.childNodes.size(); i++) {
System.out.printf(
"%02d\t%d\t\t%d%n",
i + 1,
rootNode.childNodes.get(i).score,
rootNode.childNodes.get(i).visitCount
);
System.out.printf("%02d\t%d\t\t%d%n", i + 1, rootNode.childNodes.get(i).score,
rootNode.childNodes.get(i).visitCount);
}
}
}

View File

@ -1,6 +1,6 @@
package com.thealgorithms.searches;
//URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/
// URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/
/* Order Agnostic Binary Search is an algorithm where we do not know whether the given
sorted array is ascending or descending order.
@ -11,37 +11,36 @@ package com.thealgorithms.searches;
Depending upon the condition, respective statements will be executed and we will get our answer.
*/
public class OrderAgnosticBinarySearch {
public class OrderAgnosticBinarySearch {
static int BinSearchAlgo(int[] arr, int start, int end, int target) {
static int BinSearchAlgo(int[] arr, int start, int end, int target) {
// Checking whether the given array is ascending order
boolean AscOrd = arr[start] < arr[end];
// Checking whether the given array is ascending order
boolean AscOrd = arr[start] < arr[end];
while (start <= end) {
int middle = start + (end - start) / 2;
while (start <= end) {
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
// 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 (AscOrd) {
if (arr[middle] < target)
start = middle + 1;
else
end = middle - 1;
}
// Ascending order
if (AscOrd) {
if (arr[middle] < target)
start = middle + 1;
else
end = middle - 1;
}
// Descending order
else {
if (arr[middle] > target)
start = middle + 1;
else
end = middle - 1;
}
}
// Element is not present
return -1;
}
}
// Descending order
else {
if (arr[middle] > target)
start = middle + 1;
else
end = middle - 1;
}
}
// Element is not present
return -1;
}
}

View File

@ -22,7 +22,7 @@ class PerfectBinarySearch {
public static void main(String[] args) {
PerfectBinarySearch BinarySearch = new PerfectBinarySearch();
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assert BinarySearch.binarySearch(array, -1) == -1;
assert BinarySearch.binarySearch(array, 11) == -1;
}

View File

@ -45,19 +45,12 @@ public final class QuickSelect {
return list.get(index);
}
private static <T extends Comparable<T>> int selectIndex(
List<T> list,
int n
) {
private static <T extends Comparable<T>> int selectIndex(List<T> list, int n) {
return selectIndex(list, 0, list.size() - 1, n);
}
private static <T extends Comparable<T>> int selectIndex(
List<T> list,
int left,
int right,
int n
) {
List<T> list, int left, int right, int n) {
while (true) {
if (left == right) return left;
int pivotIndex = pivot(list, left, right);
@ -73,12 +66,7 @@ public final class QuickSelect {
}
private static <T extends Comparable<T>> int partition(
List<T> list,
int left,
int right,
int pivotIndex,
int n
) {
List<T> list, int left, int right, int pivotIndex, int n) {
T pivotValue = list.get(pivotIndex);
Collections.swap(list, pivotIndex, right);
int storeIndex = left;
@ -104,11 +92,7 @@ public final class QuickSelect {
return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq);
}
private static <T extends Comparable<T>> int pivot(
List<T> list,
int left,
int right
) {
private static <T extends Comparable<T>> int pivot(List<T> list, int left, int right) {
if (right - left < 5) {
return partition5(list, left, right);
}
@ -128,11 +112,7 @@ public final class QuickSelect {
return selectIndex(list, left, rightIndex, mid);
}
private static <T extends Comparable<T>> int partition5(
List<T> list,
int left,
int right
) {
private static <T extends Comparable<T>> int partition5(List<T> list, int left, int right) {
List<T> ts = list.subList(left, right);
ts.sort(Comparator.naturalOrder());
return (left + right) >>> 1;

View File

@ -13,7 +13,7 @@ public class RabinKarpAlgorithm {
q -> A prime number
*/
public int search(String pat, String txt, int q) {
int index = -1; //note: -1 here represent not found, it is not an index
int index = -1; // note: -1 here represent not found, it is not an index
int M = pat.length();
int N = txt.length();
int i, j;

View File

@ -10,37 +10,38 @@ import com.thealgorithms.devutils.searches.MatrixSearchAlgorithm;
* {21, 31, 41, 51}}
*
* This array is sorted in both row and column manner.
* In this two pointers are taken, the first points to the 0th row and the second one points to end column, and then the
* element corresponding to the pointers placed in the array is compared with the target that either its equal, greater or
* smaller than the target. If the element is equal to the target, the co-ordinates of that element is returned i.e. an
* array of the two pointers will be returned, else if the target is greater than corresponding element then the pointer
* pointing to the 0th row will be incremented by 1, else if the target is lesser than the corresponding element then the
* pointer pointing to the end column will be decremented by 1. And if the element doesn't exist in the array, an array
* In this two pointers are taken, the first points to the 0th row and the second one points to end
* column, and then the element corresponding to the pointers placed in the array is compared with
* the target that either its equal, greater or smaller than the target. If the element is equal to
* the target, the co-ordinates of that element is returned i.e. an array of the two pointers will
* be returned, else if the target is greater than corresponding element then the pointer pointing
* to the 0th row will be incremented by 1, else if the target is lesser than the corresponding
* element then the pointer pointing to the end column will be decremented by 1. And if the element
* doesn't exist in the array, an array
* {-1, -1} will be returned.
*/
public class RowColumnWiseSorted2dArrayBinarySearch
implements MatrixSearchAlgorithm {
public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm {
@Override
public <T extends Comparable<T>> int[] find(T[][] matrix, T key) {
return search(matrix, key);
}
public static <T extends Comparable<T>> int[] search(T[][] matrix, T target) {
int rowPointer = 0; //The pointer at 0th row
int colPointer = matrix.length - 1; //The pointer at end column
while (rowPointer < matrix.length && colPointer >= 0) {
int comp = target.compareTo(matrix[rowPointer][colPointer]);
if (comp == 0) {
return new int[] { rowPointer, colPointer };
} else if (comp > 0) {
rowPointer++; //Incrementing the row pointer if the target is greater
} else {
colPointer--; //Decrementing the column pointer if the target is lesser
}
@Override
public <T extends Comparable<T>> int[] find(T[][] matrix, T key) {
return search(matrix, key);
}
public static <T extends Comparable<T>> int[] search(T[][] matrix, T target) {
int rowPointer = 0; // The pointer at 0th row
int colPointer = matrix.length - 1; // The pointer at end column
while (rowPointer < matrix.length && colPointer >= 0) {
int comp = target.compareTo(matrix[rowPointer][colPointer]);
if (comp == 0) {
return new int[] {rowPointer, colPointer};
} else if (comp > 0) {
rowPointer++; // Incrementing the row pointer if the target is greater
} else {
colPointer--; // Decrementing the column pointer if the target is lesser
}
}
return new int[] {-1, -1}; // The not found condition
}
return new int[] { -1, -1 }; //The not found condition
}
}

View File

@ -30,7 +30,7 @@ public class SaddlebackSearch {
*/
private static int[] find(int[][] arr, int row, int col, int key) {
// array to store the answer row and column
int[] ans = { -1, -1 };
int[] ans = {-1, -1};
if (row < 0 || col >= arr[row].length) {
return ans;
}

View File

@ -17,7 +17,7 @@ public class SearchInARowAndColWiseSortedMatrix {
int i = 0;
// This variable iterates over columns
int j = n - 1;
int[] result = { -1, -1 };
int[] result = {-1, -1};
while (i < n && j >= 0) {
if (matrix[i][j] == value) {
@ -30,7 +30,6 @@ public class SearchInARowAndColWiseSortedMatrix {
} else {
j--;
}
}
return result;
}

View File

@ -23,9 +23,7 @@ public class SquareRootBinarySearch {
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(
"Enter a number you want to calculate square root of : "
);
System.out.print("Enter a number you want to calculate square root of : ");
int num = sc.nextInt();
long ans = squareRoot(num);
System.out.println("The square root is : " + ans);

View File

@ -39,12 +39,7 @@ public class TernarySearch implements SearchAlgorithm {
* @param end The ending index till which we will Search.
* @return Returns the index of the Element if found. Else returns -1.
*/
private <T extends Comparable<T>> int ternarySearch(
T[] arr,
T key,
int start,
int end
) {
private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) {
if (start > end) {
return -1;
}
@ -57,15 +52,11 @@ public class TernarySearch implements SearchAlgorithm {
return mid1;
} else if (key.compareTo(arr[mid2]) == 0) {
return mid2;
} /* Search the first (1/3) rd part of the array.*/else if (
key.compareTo(arr[mid1]) < 0
) {
} /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) {
return ternarySearch(arr, key, start, --mid1);
} /* Search 3rd (1/3)rd part of the array */else if (
key.compareTo(arr[mid2]) > 0
) {
} /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) {
return ternarySearch(arr, key, ++mid2, end);
} /* Search middle (1/3)rd part of the array */else {
} /* Search middle (1/3)rd part of the array */ else {
return ternarySearch(arr, key, mid1, mid2);
}
}
@ -75,11 +66,10 @@ public class TernarySearch implements SearchAlgorithm {
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[]::new);
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.toArray(Integer[] ::new);
// the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
@ -87,15 +77,11 @@ public class TernarySearch implements SearchAlgorithm {
TernarySearch search = new TernarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.printf(
"Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
);
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound, integers[atIndex], atIndex, size);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
System.out.printf(
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}

View File

@ -61,27 +61,19 @@ public class UnionFind {
// Tests
public static void main(String[] args) {
UnionFind uf = new UnionFind(5);
System.out.println(
"init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):"
);
System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):");
System.out.println(uf);
uf.union(1, 2);
System.out.println(
"union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):"
);
System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):");
System.out.println(uf);
uf.union(3, 4);
System.out.println(
"union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"
);
System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):");
System.out.println(uf);
uf.find(4);
System.out.println(
"find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"
);
System.out.println("find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):");
System.out.println(uf);
System.out.println("count (should print '3'):");

View File

@ -33,12 +33,11 @@ class UpperBound implements SearchAlgorithm {
int size = 100;
int maxElement = 100000;
Integer[] integers = IntStream
.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[]::new);
Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement))
.limit(size)
.sorted()
.boxed()
.toArray(Integer[] ::new);
// The element for which the upper bound is to be found
int val = integers[r.nextInt(size - 1)] + 1;
@ -46,16 +45,12 @@ class UpperBound implements SearchAlgorithm {
UpperBound search = new UpperBound();
int atIndex = search.find(integers, val);
System.out.printf(
"Val: %d. Upper Bound Found %d at index %d. An array length %d%n",
val,
integers[atIndex],
atIndex,
size
);
System.out.printf("Val: %d. Upper Bound Found %d at index %d. An array length %d%n", val,
integers[atIndex], atIndex, size);
boolean toCheck = integers[atIndex] > val || integers[size - 1] < val;
System.out.printf("Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
System.out.printf(
"Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
}
/**
@ -78,12 +73,7 @@ class UpperBound implements SearchAlgorithm {
* @param right The upper bound
* @return the location of the key
*/
private <T extends Comparable<T>> int search(
T[] array,
T key,
int left,
int right
) {
private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) {
if (right <= left) {
return left;
}

View File

@ -1,31 +1,29 @@
package com.thealgorithms.searches;
import java.util.*;
public class sortOrderAgnosticBinarySearch {
public static int find(int[] arr, int key){
public static int find(int[] arr, int key) {
int start = 0;
int end = arr.length-1;
boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order.
while(start<=end){
int mid = end-start/2;
if (arr[mid]==key){
int end = arr.length - 1;
boolean arrDescending = arr[start]
> arr[end]; // checking for Array is in ascending order or descending order.
while (start <= end) {
int mid = end - start / 2;
if (arr[mid] == key) {
return mid;
}
if(arrDescending){ // boolean is true then our array is in descending order
if(key<arr[mid]){
start=mid+1;
if (arrDescending) { // boolean is true then our array is in descending order
if (key < arr[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
else{
end=mid-1;
} else { // otherwise our array is in ascending order
if (key > arr[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
else { // otherwise our array is in ascending order
if(key>arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
}
}
return -1;
}