mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-22 11:46:34 +08:00
Format code with prettier (#3375)
This commit is contained in:
@ -2,11 +2,11 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* Binary search is one of the most popular algorithms The algorithm finds the
|
||||
@ -43,7 +43,12 @@ 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
|
||||
}
|
||||
@ -68,12 +73,12 @@ 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)];
|
||||
@ -82,13 +87,22 @@ class BinarySearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
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.
|
||||
@ -6,69 +7,81 @@ If that element is equal to target, its coordinates are returned, else if it is
|
||||
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
|
||||
{
|
||||
static int[] BinarySearch(int[][] arr, int target){
|
||||
public class BinarySearch2dArray {
|
||||
|
||||
static int[] BinarySearch(int[][] arr, int target) {
|
||||
int rowCount = arr.length, colCount = arr[0].length;
|
||||
|
||||
if (rowCount == 1){
|
||||
if (rowCount == 1) {
|
||||
return binarySearch(arr, target, 0, 0, colCount);
|
||||
}
|
||||
|
||||
int startRow = 0, endRow = rowCount - 1, midCol = colCount/2;
|
||||
int startRow = 0, endRow = rowCount - 1, midCol = colCount / 2;
|
||||
|
||||
while (startRow < endRow - 1){
|
||||
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;
|
||||
if (arr[midRow][midCol] == target) {
|
||||
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 (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){
|
||||
|
||||
while (colStart <= 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 };
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
import com.thealgorithms.searches.DepthFirstSearch.Node;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
@ -38,24 +37,33 @@ public class BreadthFirstSearch {
|
||||
|
||||
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));
|
||||
throw new AssertionError(
|
||||
String.format("expected=%s but was actual=%s", expected, actual)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(final String[] args) {
|
||||
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")
|
||||
)))),
|
||||
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")
|
||||
));
|
||||
)
|
||||
);
|
||||
|
||||
{
|
||||
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);
|
||||
}
|
||||
@ -64,7 +72,7 @@ public class BreadthFirstSearch {
|
||||
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);
|
||||
}
|
||||
@ -73,7 +81,7 @@ public class BreadthFirstSearch {
|
||||
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);
|
||||
}
|
||||
|
@ -40,33 +40,43 @@ public class DepthFirstSearch {
|
||||
return Optional.of(node);
|
||||
}
|
||||
|
||||
return node.getSubNodes()
|
||||
.stream()
|
||||
.map(value -> search(value, name))
|
||||
.flatMap(Optional::stream)
|
||||
.findAny();
|
||||
return node
|
||||
.getSubNodes()
|
||||
.stream()
|
||||
.map(value -> search(value, name))
|
||||
.flatMap(Optional::stream)
|
||||
.findAny();
|
||||
}
|
||||
|
||||
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));
|
||||
throw new AssertionError(
|
||||
String.format("expected=%s but was actual=%s", expected, actual)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(final String[] args) {
|
||||
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")
|
||||
)))),
|
||||
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")
|
||||
));
|
||||
)
|
||||
);
|
||||
|
||||
{
|
||||
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);
|
||||
}
|
||||
@ -75,7 +85,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);
|
||||
}
|
||||
@ -84,7 +94,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);
|
||||
}
|
||||
|
@ -1,12 +1,12 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
class ExponentialSearch implements SearchAlgorithm {
|
||||
|
||||
@ -16,12 +16,12 @@ 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)];
|
||||
@ -30,15 +30,23 @@ class ExponentialSearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -56,6 +64,11 @@ 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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -3,12 +3,12 @@ package com.thealgorithms.searches;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/*
|
||||
* Fibonacci Search is a popular algorithm which finds the position of a target value in
|
||||
* a sorted array
|
||||
*
|
||||
* The time complexity for this search algorithm is O(log3(n))
|
||||
* The space complexity for this search algorithm is O(1)
|
||||
* @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru)
|
||||
* Fibonacci Search is a popular algorithm which finds the position of a target value in
|
||||
* a sorted array
|
||||
*
|
||||
* The time complexity for this search algorithm is O(log3(n))
|
||||
* The space complexity for this search algorithm is O(1)
|
||||
* @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru)
|
||||
*/
|
||||
public class FibonacciSearch implements SearchAlgorithm {
|
||||
|
||||
@ -59,7 +59,7 @@ 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;
|
||||
@ -67,7 +67,14 @@ public class FibonacciSearch implements SearchAlgorithm {
|
||||
int atIndex = fsearch.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
"Should be found: " + shouldBeFound + ". Found " + integers[atIndex] + " at index " + atIndex + ". An array length " + size);
|
||||
"Should be found: " +
|
||||
shouldBeFound +
|
||||
". Found " +
|
||||
integers[atIndex] +
|
||||
" at index " +
|
||||
atIndex +
|
||||
". An array length " +
|
||||
size
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -33,9 +33,10 @@ 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();
|
||||
|
||||
}
|
||||
|
||||
public static int rotated(int[] a) {
|
||||
|
@ -32,7 +32,12 @@ 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) {
|
||||
@ -55,7 +60,11 @@ 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
|
||||
Integer shouldBeFound = integers[r.nextInt(size - 1)];
|
||||
@ -64,13 +73,22 @@ class InterpolationSearch {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -2,10 +2,10 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* Binary search is one of the most popular algorithms This class represents
|
||||
@ -60,8 +60,11 @@ 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,13 +73,22 @@ public final class IterativeBinarySearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -2,10 +2,10 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* A iterative version of a ternary search algorithm This is better way to
|
||||
@ -31,7 +31,6 @@ public class IterativeTernarySearch implements SearchAlgorithm {
|
||||
int right = array.length - 1;
|
||||
|
||||
while (right > left) {
|
||||
|
||||
int leftCmp = array[left].compareTo(key);
|
||||
int rightCmp = array[right].compareTo(key);
|
||||
if (leftCmp == 0) {
|
||||
@ -59,8 +58,11 @@ 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)];
|
||||
@ -69,13 +71,22 @@ public class IterativeTernarySearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -1,20 +1,20 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
class KMPSearch {
|
||||
int KMPSearch(String pat, String txt)
|
||||
{
|
||||
|
||||
int KMPSearch(String pat, String txt) {
|
||||
int M = pat.length();
|
||||
int N = txt.length();
|
||||
|
||||
|
||||
// create lps[] that will hold the longest
|
||||
// prefix suffix values for pattern
|
||||
int lps[] = new int[M];
|
||||
int j = 0; // index for pat[]
|
||||
|
||||
|
||||
// Preprocess the pattern (calculate lps[]
|
||||
// array)
|
||||
computeLPSArray(pat, M, lps);
|
||||
|
||||
|
||||
int i = 0; // index for txt[]
|
||||
while ((N - i) >= (M - j)) {
|
||||
if (pat.charAt(j) == txt.charAt(i)) {
|
||||
@ -22,62 +22,48 @@ 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;
|
||||
|
||||
}
|
||||
|
||||
// mismatch after j matches
|
||||
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");
|
||||
return -1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void computeLPSArray(String pat, int M, int lps[])
|
||||
{
|
||||
|
||||
void computeLPSArray(String pat, int M, int lps[]) {
|
||||
// length of the previous longest prefix suffix
|
||||
int len = 0;
|
||||
int i = 1;
|
||||
lps[0] = 0; // lps[0] is always 0
|
||||
|
||||
|
||||
// the loop calculates lps[i] for i = 1 to M-1
|
||||
while (i < M) {
|
||||
if (pat.charAt(i) == pat.charAt(len)) {
|
||||
len++;
|
||||
lps[i] = len;
|
||||
i++;
|
||||
}
|
||||
else // (pat[i] != pat[len])
|
||||
{
|
||||
} else { // (pat[i] != pat[len])
|
||||
// This is tricky. Consider the example.
|
||||
// AAACAAAA and i = 7. The idea is similar
|
||||
// to search step.
|
||||
if (len != 0) {
|
||||
len = lps[len - 1];
|
||||
|
||||
// Also, note that we do not increment
|
||||
// i here
|
||||
}
|
||||
else // if (len == 0)
|
||||
{
|
||||
} else { // if (len == 0)
|
||||
lps[i] = len;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
// This code has been contributed by Amit Khandelwal.
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* Linear search is the easiest search algorithm It works with sorted and
|
||||
@ -42,8 +42,10 @@ 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)];
|
||||
@ -52,8 +54,13 @@ public class LinearSearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
String.format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ package com.thealgorithms.searches;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class LinearSearchThread {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] list = new int[200];
|
||||
for (int j = 0; j < list.length; j++) {
|
||||
@ -28,14 +29,15 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
class Searcher extends Thread {
|
||||
|
||||
private final int[] arr;
|
||||
private final int left, right;
|
||||
private final int x;
|
||||
|
@ -2,10 +2,10 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* The LowerBound method is used to return an index pointing to the first
|
||||
@ -35,12 +35,12 @@ 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;
|
||||
@ -49,14 +49,23 @@ class LowerBound implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, val);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Val: %d. Lower Bound Found %d at index %d. An array length %d",
|
||||
val, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Val: %d. Lower Bound Found %d at index %d. An array length %d",
|
||||
val,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val;
|
||||
System.out.println(
|
||||
format(
|
||||
"Lower Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck));
|
||||
format(
|
||||
"Lower Bound found at an index: %d. Is greater or max element: %b",
|
||||
atIndex,
|
||||
toCheck
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -79,7 +88,12 @@ 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;
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Random;
|
||||
|
||||
@ -23,8 +23,7 @@ public class MonteCarloTreeSearch {
|
||||
int score;
|
||||
int visitCount;
|
||||
|
||||
public Node() {
|
||||
}
|
||||
public Node() {}
|
||||
|
||||
public Node(Node parent, boolean isPlayersTurn) {
|
||||
this.parent = parent;
|
||||
@ -78,7 +77,10 @@ public class MonteCarloTreeSearch {
|
||||
|
||||
winnerNode = getWinnerNode(rootNode);
|
||||
printScores(rootNode);
|
||||
System.out.format("\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1);
|
||||
System.out.format(
|
||||
"\nThe optimal node is: %02d\n",
|
||||
rootNode.childNodes.indexOf(winnerNode) + 1
|
||||
);
|
||||
|
||||
return winnerNode;
|
||||
}
|
||||
@ -118,8 +120,13 @@ 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;
|
||||
@ -148,7 +155,7 @@ public class MonteCarloTreeSearch {
|
||||
// To use the MCTS algorithm correctly this should be a simulation of the nodes' current
|
||||
// state of the game until it finishes (if possible) and use an evaluation function to
|
||||
// determine how good or bad the play was.
|
||||
// e.g. Play tic tac toe choosing random squares until the game ends.
|
||||
// e.g. Play tic tac toe choosing random squares until the game ends.
|
||||
promisingNode.playerWon = (rand.nextInt(6) == 0);
|
||||
|
||||
isPlayerWinner = promisingNode.playerWon;
|
||||
@ -158,8 +165,10 @@ 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;
|
||||
}
|
||||
|
||||
@ -168,15 +177,24 @@ 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.println(String.format("%02d\t%d\t\t%d", i + 1,
|
||||
rootNode.childNodes.get(i).score, rootNode.childNodes.get(i).visitCount));
|
||||
System.out.println(
|
||||
String.format(
|
||||
"%02d\t%d\t\t%d",
|
||||
i + 1,
|
||||
rootNode.childNodes.get(i).score,
|
||||
rootNode.childNodes.get(i).visitCount
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
}
|
||||
|
@ -45,19 +45,21 @@ 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;
|
||||
if (left == right) return left;
|
||||
int pivotIndex = pivot(list, left, right);
|
||||
pivotIndex = partition(list, left, right, pivotIndex, n);
|
||||
if (n == pivotIndex) {
|
||||
@ -71,11 +73,11 @@ 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);
|
||||
@ -99,15 +101,13 @@ public final class QuickSelect {
|
||||
|
||||
Collections.swap(list, right, storeIndexEq);
|
||||
|
||||
return (n < storeIndex)
|
||||
? storeIndex
|
||||
: Math.min(n, storeIndexEq);
|
||||
return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq);
|
||||
}
|
||||
|
||||
private static <T extends Comparable<T>> int pivot(
|
||||
List<T> list,
|
||||
int left,
|
||||
int right
|
||||
List<T> list,
|
||||
int left,
|
||||
int right
|
||||
) {
|
||||
if (right - left < 5) {
|
||||
return partition5(list, left, right);
|
||||
@ -129,9 +129,9 @@ public final class QuickSelect {
|
||||
}
|
||||
|
||||
private static <T extends Comparable<T>> int partition5(
|
||||
List<T> list,
|
||||
int left,
|
||||
int right
|
||||
List<T> list,
|
||||
int left,
|
||||
int right
|
||||
) {
|
||||
List<T> ts = list.subList(left, right);
|
||||
ts.sort(Comparator.naturalOrder());
|
||||
|
@ -1,77 +1,66 @@
|
||||
package com.thealgorithms.searches;
|
||||
// Following program is a Java implementation
|
||||
|
||||
// Following program is a Java implementation
|
||||
// of Rabin Karp Algorithm given in the CLRS book
|
||||
|
||||
public class RabinKarpAlgorithm
|
||||
{
|
||||
|
||||
public class RabinKarpAlgorithm {
|
||||
|
||||
// d is the number of characters in the input alphabet
|
||||
public final static int d = 256;
|
||||
|
||||
public static final int d = 256;
|
||||
|
||||
/* pat -> pattern
|
||||
txt -> text
|
||||
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
|
||||
public int search(String pat, String txt, int q) {
|
||||
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;
|
||||
int p = 0; // hash value for pattern
|
||||
int t = 0; // hash value for txt
|
||||
int h = 1;
|
||||
|
||||
|
||||
// The value of h would be "pow(d, M-1)%q"
|
||||
for (i = 0; i < M-1; i++)
|
||||
h = (h*d)%q;
|
||||
|
||||
for (i = 0; i < M - 1; i++) h = (h * d) % q;
|
||||
|
||||
// Calculate the hash value of pattern and first
|
||||
// window of text
|
||||
for (i = 0; i < M; i++)
|
||||
{
|
||||
p = (d*p + pat.charAt(i))%q;
|
||||
t = (d*t + txt.charAt(i))%q;
|
||||
for (i = 0; i < M; i++) {
|
||||
p = (d * p + pat.charAt(i)) % q;
|
||||
t = (d * t + txt.charAt(i)) % q;
|
||||
}
|
||||
|
||||
|
||||
// Slide the pattern over text one by one
|
||||
for (i = 0; i <= N - M; i++)
|
||||
{
|
||||
|
||||
for (i = 0; i <= N - M; i++) {
|
||||
// Check the hash values of current window of text
|
||||
// and pattern. If the hash values match then only
|
||||
// check for characters one by one
|
||||
if ( p == t )
|
||||
{
|
||||
if (p == t) {
|
||||
/* Check for characters one by one */
|
||||
for (j = 0; j < M; j++)
|
||||
{
|
||||
if (txt.charAt(i+j) != pat.charAt(j))
|
||||
break;
|
||||
for (j = 0; j < M; j++) {
|
||||
if (txt.charAt(i + j) != pat.charAt(j)) break;
|
||||
}
|
||||
|
||||
|
||||
// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
|
||||
if (j == M) {
|
||||
System.out.println("Pattern found at index " + i);
|
||||
index= i;
|
||||
return index ;
|
||||
index = i;
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Calculate hash value for next window of text: Remove
|
||||
// leading digit, add trailing digit
|
||||
if ( i < N-M )
|
||||
{
|
||||
t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q;
|
||||
|
||||
if (i < N - M) {
|
||||
t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q;
|
||||
|
||||
// We might get negative value of t, converting it
|
||||
// to positive
|
||||
if (t < 0)
|
||||
t = (t + q);
|
||||
if (t < 0) t = (t + q);
|
||||
}
|
||||
}
|
||||
return index; // return -1 if pattern does not found
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// This code is contributed by nuclode
|
||||
|
@ -29,9 +29,8 @@ public class SaddlebackSearch {
|
||||
* -1 -1.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
@ -23,7 +23,9 @@ 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);
|
||||
|
@ -2,10 +2,10 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* A ternary search algorithm is a technique in computer science for finding the
|
||||
@ -41,7 +41,12 @@ 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;
|
||||
}
|
||||
@ -54,11 +59,15 @@ 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);
|
||||
}
|
||||
}
|
||||
@ -68,8 +77,11 @@ 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)];
|
||||
@ -78,13 +90,22 @@ public class TernarySearch implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.println(
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
|
||||
format(
|
||||
"Found by system method at an index: %d. Is equal: %b",
|
||||
toCheck,
|
||||
toCheck == atIndex
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -61,19 +61,27 @@ 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'):");
|
||||
|
@ -2,10 +2,10 @@ package com.thealgorithms.searches;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
|
||||
/**
|
||||
* The UpperBound method is used to return an index pointing to the first
|
||||
@ -35,12 +35,12 @@ 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;
|
||||
@ -49,14 +49,23 @@ class UpperBound implements SearchAlgorithm {
|
||||
int atIndex = search.find(integers, val);
|
||||
|
||||
System.out.println(
|
||||
format(
|
||||
"Val: %d. Upper Bound Found %d at index %d. An array length %d",
|
||||
val, integers[atIndex], atIndex, size));
|
||||
format(
|
||||
"Val: %d. Upper Bound Found %d at index %d. An array length %d",
|
||||
val,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
)
|
||||
);
|
||||
|
||||
boolean toCheck = integers[atIndex] > val || integers[size - 1] < val;
|
||||
System.out.println(
|
||||
format(
|
||||
"Upper Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck));
|
||||
format(
|
||||
"Upper Bound found at an index: %d. Is greater or max element: %b",
|
||||
atIndex,
|
||||
toCheck
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -79,7 +88,12 @@ 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;
|
||||
}
|
||||
|
Reference in New Issue
Block a user