Refactor Code Style (#4151)

This commit is contained in:
Saurabh Rahate
2023-04-15 13:55:54 +05:30
committed by GitHub
parent 1ce907625b
commit 1dc388653a
100 changed files with 293 additions and 319 deletions

View File

@ -91,7 +91,7 @@ public class AllPathsFromSourceToTarget {
} }
// Driver program // Driver program
public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int a[][], int source, int destination) public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination)
{ {
// Create a sample graph // Create a sample graph
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices); AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);

View File

@ -11,7 +11,7 @@ package com.thealgorithms.ciphers;
public class Blowfish { public class Blowfish {
//Initializing substitution boxes //Initializing substitution boxes
String S[][] = { String[][] S = {
{ {
"d1310ba6", "d1310ba6",
"98dfb5ac", "98dfb5ac",
@ -1047,7 +1047,7 @@ public class Blowfish {
}; };
//Initializing subkeys with digits of pi //Initializing subkeys with digits of pi
String P[] = { String[] P = {
"243f6a88", "243f6a88",
"85a308d3", "85a308d3",
"13198a2e", "13198a2e",
@ -1146,7 +1146,7 @@ public class Blowfish {
The outputs are added modulo 232 and XORed to produce the final 32-bit output The outputs are added modulo 232 and XORed to produce the final 32-bit output
*/ */
private String f(String plainText) { private String f(String plainText) {
String a[] = new String[4]; String[] a = new String[4];
String ans = ""; String ans = "";
for (int i = 0; i < 8; i += 2) { for (int i = 0; i < 8; i += 2) {
//column number for S-box is a 8-bit value //column number for S-box is a 8-bit value

View File

@ -22,7 +22,7 @@ public class HillCipher {
System.out.println("Enter key matrix size"); System.out.println("Enter key matrix size");
int matrixSize = userInput.nextInt(); int matrixSize = userInput.nextInt();
System.out.println("Enter Key/encryptionKey matrix "); System.out.println("Enter Key/encryptionKey matrix ");
int keyMatrix[][] = new int[matrixSize][matrixSize]; int[][] keyMatrix = new int[matrixSize][matrixSize];
for (int i = 0; i < matrixSize; i++) { for (int i = 0; i < matrixSize; i++) {
for (int j = 0; j < matrixSize; j++) { for (int j = 0; j < matrixSize; j++) {
keyMatrix[i][j] = userInput.nextInt(); keyMatrix[i][j] = userInput.nextInt();
@ -33,7 +33,7 @@ public class HillCipher {
int[][] messageVector = new int[matrixSize][1]; int[][] messageVector = new int[matrixSize][1];
String CipherText = ""; String CipherText = "";
int cipherMatrix[][] = new int[matrixSize][1]; int[][] cipherMatrix = new int[matrixSize][1];
int j = 0; int j = 0;
while (j < message.length()) { while (j < message.length()) {
for (int i = 0; i < matrixSize; i++) { for (int i = 0; i < matrixSize; i++) {
@ -69,7 +69,7 @@ public class HillCipher {
System.out.println("Enter key matrix size"); System.out.println("Enter key matrix size");
int n = userInput.nextInt(); int n = userInput.nextInt();
System.out.println("Enter inverseKey/decryptionKey matrix "); System.out.println("Enter inverseKey/decryptionKey matrix ");
int keyMatrix[][] = new int[n][n]; int[][] keyMatrix = new int[n][n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
keyMatrix[i][j] = userInput.nextInt(); keyMatrix[i][j] = userInput.nextInt();
@ -81,7 +81,7 @@ public class HillCipher {
//solving for the required plaintext message //solving for the required plaintext message
int[][] messageVector = new int[n][1]; int[][] messageVector = new int[n][1];
String PlainText = ""; String PlainText = "";
int plainMatrix[][] = new int[n][1]; int[][] plainMatrix = new int[n][1];
int j = 0; int j = 0;
while (j < message.length()) { while (j < message.length()) {
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
@ -111,13 +111,13 @@ public class HillCipher {
} }
// Determinant calculator // Determinant calculator
public static int determinant(int a[][], int n) { public static int determinant(int[][] a, int n) {
int det = 0, sign = 1, p = 0, q = 0; int det = 0, sign = 1, p = 0, q = 0;
if (n == 1) { if (n == 1) {
det = a[0][0]; det = a[0][0];
} else { } else {
int b[][] = new int[n - 1][n - 1]; int[][] b = new int[n - 1][n - 1];
for (int x = 0; x < n; x++) { for (int x = 0; x < n; x++) {
p = 0; p = 0;
q = 0; q = 0;

View File

@ -4,7 +4,7 @@ import java.util.Scanner;
class ProductCipher { class ProductCipher {
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Enter the input to be encrypted: "); System.out.println("Enter the input to be encrypted: ");
String substitutionInput = sc.nextLine(); String substitutionInput = sc.nextLine();

View File

@ -23,7 +23,7 @@ class BinaryToDecimal {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.print("Binary number: "); System.out.print("Binary number: ");
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong())); System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));

View File

@ -14,7 +14,7 @@ public class BinaryToOctal {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: "); System.out.println("Input the binary number: ");
int b = sc.nextInt(); int b = sc.nextInt();

View File

@ -12,7 +12,7 @@ class DecimalToBinary {
* *
* @param args Command Line Arguments * @param args Command Line Arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
conventionalConversion(); conventionalConversion();
bitwiseConversion(); bitwiseConversion();
} }

View File

@ -52,7 +52,7 @@ public class HexToOct {
* *
* @param args arguments * @param args arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
String hexadecnum; String hexadecnum;
int decnum, octalnum; int decnum, octalnum;
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);

View File

@ -17,7 +17,7 @@ public class HexaDecimalToDecimal {
} }
// Main method gets the hexadecimal input from user and converts it into Decimal output. // Main method gets the hexadecimal input from user and converts it into Decimal output.
public static void main(String args[]) { public static void main(String[] args) {
String hexa_Input; String hexa_Input;
int dec_output; int dec_output;
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);

View File

@ -14,7 +14,7 @@ public class OctalToDecimal {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.print("Octal Input: "); System.out.print("Octal Input: ");
String inputOctal = sc.nextLine(); String inputOctal = sc.nextLine();

View File

@ -46,7 +46,7 @@ public class OctalToHexadecimal {
return hex; return hex;
} }
public static void main(String args[]) { public static void main(String[] args) {
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
System.out.print("Enter the Octal number: "); System.out.print("Enter the Octal number: ");
// Take octal number as input from user in a string // Take octal number as input from user in a string

View File

@ -14,7 +14,7 @@ public class TurkishToLatinConversion {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Input the string: "); System.out.println("Input the string: ");
String b = sc.next(); String b = sc.next();

View File

@ -59,9 +59,8 @@ public class Bag<Element> implements Iterable<Element> {
* @return true if bag contains element, otherwise false * @return true if bag contains element, otherwise false
*/ */
public boolean contains(Element element) { public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator(); for (Element value : this) {
while (iterator.hasNext()) { if (value.equals(element)) {
if (iterator.next().equals(element)) {
return true; return true;
} }
} }

View File

@ -6,7 +6,7 @@ class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Gr
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{ start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
int vertex, edge; int vertex, edge;
private Edge edges[]; private Edge[] edges;
private int index = 0; private int index = 0;
BellmanFord(int v, int e) { BellmanFord(int v, int e) {
@ -36,7 +36,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
* @param p[] Parent array which shows updates in edges * @param p[] Parent array which shows updates in edges
* @param i Current vertex under consideration * @param i Current vertex under consideration
*/ */
void printPath(int p[], int i) { void printPath(int[] p, int i) {
if (p[i] == -1) { // Found the path back to parent if (p[i] == -1) { // Found the path back to parent
return; return;
} }
@ -44,7 +44,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
System.out.print(i + " "); System.out.print(i + " ");
} }
public static void main(String args[]) { public static void main(String[] args) {
BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables
obj.go(); obj.go();
} }
@ -55,7 +55,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
System.out.println("Enter no. of vertices and edges please"); System.out.println("Enter no. of vertices and edges please");
v = sc.nextInt(); v = sc.nextInt();
e = sc.nextInt(); e = sc.nextInt();
Edge arr[] = new Edge[e]; // Array of edges Edge[] arr = new Edge[e]; // Array of edges
System.out.println("Input edges"); System.out.println("Input edges");
for (i = 0; i < e; i++) { for (i = 0; i < e; i++) {
u = sc.nextInt(); u = sc.nextInt();
@ -63,9 +63,9 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
w = sc.nextInt(); w = sc.nextInt();
arr[i] = new Edge(u, ve, w); arr[i] = new Edge(u, ve, w);
} }
int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices // and all vertices
int p[] = new int[v]; // Parent array for holding the paths int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
dist[i] = Integer.MAX_VALUE; // Initializing distance values dist[i] = Integer.MAX_VALUE; // Initializing distance values
} }
@ -113,11 +113,11 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
* @param end Ending vertex * @param end Ending vertex
* @param Edge Array of edges * @param Edge Array of edges
*/ */
public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
int i, j, v = vertex, e = edge, neg = 0; int i, j, v = vertex, e = edge, neg = 0;
double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source double[] dist = new double[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices // and all vertices
int p[] = new int[v]; // Parent array for holding the paths int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
dist[i] = Integer.MAX_VALUE; // Initializing distance values dist[i] = Integer.MAX_VALUE; // Initializing distance values
} }

View File

@ -8,7 +8,7 @@ class dijkstras {
int k = 9; int k = 9;
int minDist(int dist[], Boolean Set[]) { int minDist(int[] dist, Boolean[] Set) {
int min = Integer.MAX_VALUE, min_index = -1; int min = Integer.MAX_VALUE, min_index = -1;
for (int r = 0; r < k; r++) { for (int r = 0; r < k; r++) {
@ -21,16 +21,16 @@ class dijkstras {
return min_index; return min_index;
} }
void print(int dist[]) { void print(int[] dist) {
System.out.println("Vertex \t\t Distance"); System.out.println("Vertex \t\t Distance");
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
System.out.println(i + " \t " + dist[i]); System.out.println(i + " \t " + dist[i]);
} }
} }
void dijkstra(int graph[][], int src) { void dijkstra(int[][] graph, int src) {
int dist[] = new int[k]; int[] dist = new int[k];
Boolean Set[] = new Boolean[k]; Boolean[] Set = new Boolean[k];
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
dist[i] = Integer.MAX_VALUE; dist[i] = Integer.MAX_VALUE;
@ -60,7 +60,7 @@ class dijkstras {
} }
public static void main(String[] args) { public static void main(String[] args) {
int graph[][] = new int[][] { int[][] graph = new int[][] {
{ 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 },

View File

@ -4,7 +4,7 @@ import java.util.Scanner;
public class FloydWarshall { public class FloydWarshall {
private int DistanceMatrix[][]; private int[][] DistanceMatrix;
private int numberofvertices; // number of vertices in the graph private int numberofvertices; // number of vertices in the graph
public static final int INFINITY = 999; public static final int INFINITY = 999;
@ -15,7 +15,7 @@ public class FloydWarshall {
this.numberofvertices = numberofvertices; this.numberofvertices = numberofvertices;
} }
public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
for ( for (
int destination = 1; int destination = 1;

View File

@ -122,7 +122,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
public class Graphs { public class Graphs {
public static void main(String args[]) { public static void main(String[] args) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>(); AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
assert graph.addEdge(1, 2); assert graph.addEdge(1, 2);
assert graph.addEdge(1, 5); assert graph.addEdge(1, 5);

View File

@ -83,7 +83,7 @@ public class Kosaraju {
} }
private void sortEdgesByLowestFinishTime(int v, List<List<Integer>> list){ private void sortEdgesByLowestFinishTime(int v, List<List<Integer>> list){
int vis[] = new int[v]; int[] vis = new int[v];
for (int i = 0; i < v; i++) { for (int i = 0; i < v; i++) {
if(vis[i] == 0){ if(vis[i] == 0){
dfs(i, vis, list); dfs(i, vis, list);
@ -110,7 +110,7 @@ public class Kosaraju {
* @param transposeGraph Transpose of the given adjacency list * @param transposeGraph Transpose of the given adjacency list
*/ */
public void findStronglyConnectedComponents(int v, List<List<Integer>> transposeGraph){ public void findStronglyConnectedComponents(int v, List<List<Integer>> transposeGraph){
int vis[] = new int[v]; int[] vis = new int[v];
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
var node = stack.pop(); var node = stack.pop();
if(vis[node] == 0){ if(vis[node] == 0){
@ -122,7 +122,7 @@ public class Kosaraju {
} }
//Dfs to store the nodes in order of lowest finish time //Dfs to store the nodes in order of lowest finish time
private void dfs(int node, int vis[], List<List<Integer>> list){ private void dfs(int node, int[] vis, List<List<Integer>> list){
vis[node] = 1; vis[node] = 1;
for(Integer neighbour : list.get(node)){ for(Integer neighbour : list.get(node)){
if(vis[neighbour] == 0) if(vis[neighbour] == 0)
@ -132,7 +132,7 @@ public class Kosaraju {
} }
//Dfs to find all the nodes of each strongly connected component //Dfs to find all the nodes of each strongly connected component
private void dfs2(int node, int vis[], List<List<Integer>> list){ private void dfs2(int node, int[] vis, List<List<Integer>> list){
vis[node] = 1; vis[node] = 1;
for(Integer neighbour : list.get(node)){ for(Integer neighbour : list.get(node)){
if(vis[neighbour] == 0) if(vis[neighbour] == 0)

View File

@ -14,7 +14,7 @@ import java.util.Queue;
*/ */
public class MatrixGraphs { public class MatrixGraphs {
public static void main(String args[]) { public static void main(String[] args) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10); AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2); graph.addEdge(1, 2);
graph.addEdge(1, 5); graph.addEdge(1, 5);

View File

@ -12,7 +12,7 @@ class PrimMST {
// A utility function to find the vertex with minimum key // A utility function to find the vertex with minimum key
// value, from the set of vertices not yet included in MST // value, from the set of vertices not yet included in MST
int minKey(int key[], Boolean mstSet[]) { int minKey(int[] key, Boolean[] mstSet) {
// Initialize min value // Initialize min value
int min = Integer.MAX_VALUE, min_index = -1; int min = Integer.MAX_VALUE, min_index = -1;
@ -28,7 +28,7 @@ class PrimMST {
// A utility function to print the constructed MST stored in // A utility function to print the constructed MST stored in
// parent[] // parent[]
void printMST(int parent[], int n, int graph[][]) { void printMST(int[] parent, int n, int[][] graph) {
System.out.println("Edge Weight"); System.out.println("Edge Weight");
for (int i = 1; i < V; i++) { for (int i = 1; i < V; i++) {
System.out.println( System.out.println(
@ -39,15 +39,15 @@ class PrimMST {
// Function to construct and print MST for a graph represented // Function to construct and print MST for a graph represented
// using adjacency matrix representation // using adjacency matrix representation
void primMST(int graph[][]) { void primMST(int[][] graph) {
// Array to store constructed MST // Array to store constructed MST
int parent[] = new int[V]; int[] parent = new int[V];
// Key values used to pick minimum weight edge in cut // Key values used to pick minimum weight edge in cut
int key[] = new int[V]; int[] key = new int[V];
// To represent set of vertices not yet included in MST // To represent set of vertices not yet included in MST
Boolean mstSet[] = new Boolean[V]; Boolean[] mstSet = new Boolean[V];
// Initialize all keys as INFINITE // Initialize all keys as INFINITE
for (int i = 0; i < V; i++) { for (int i = 0; i < V; i++) {
@ -103,7 +103,7 @@ class PrimMST {
(3)-------(4) (3)-------(4)
9 */ 9 */
PrimMST t = new PrimMST(); PrimMST t = new PrimMST();
int graph[][] = new int[][] { int[][] graph = new int[][] {
{ 0, 2, 0, 6, 0 }, { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 }, { 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 }, { 0, 3, 0, 0, 7 },

View File

@ -68,15 +68,15 @@ public class TarjansAlgorithm {
// lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can
// be reached from a subtree rooted with a particular node. // be reached from a subtree rooted with a particular node.
int lowTime[] = new int[V]; int[] lowTime = new int[V];
int insertionTime[] = new int[V]; int[] insertionTime = new int[V];
for (int i = 0; i < V; i++) { for (int i = 0; i < V; i++) {
insertionTime[i] = -1; insertionTime[i] = -1;
lowTime[i] = -1; lowTime[i] = -1;
} }
// To check if element is present in stack // To check if element is present in stack
boolean isInStack[] = new boolean[V]; boolean[] isInStack = new boolean[V];
// Store nodes during DFS // Store nodes during DFS
Stack<Integer> st = new Stack<Integer>(); Stack<Integer> st = new Stack<Integer>();
@ -89,8 +89,8 @@ public class TarjansAlgorithm {
return SCClist; return SCClist;
} }
private void stronglyConnCompsUtil(int u, int lowTime[], int insertionTime[], private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
boolean isInStack[], Stack<Integer> st, List<List<Integer>> graph) { boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
// Initialize insertion time and lowTime value of current node // Initialize insertion time and lowTime value of current node
insertionTime[u] = Time; insertionTime[u] = Time;
@ -101,22 +101,16 @@ public class TarjansAlgorithm {
isInStack[u] = true; isInStack[u] = true;
st.push(u); st.push(u);
int n;
// Go through all vertices adjacent to this // Go through all vertices adjacent to this
Iterator<Integer> i = graph.get(u).iterator(); for (Integer vertex : graph.get(u)) {
while (i.hasNext()) {
n = i.next();
//If the adjacent node is unvisited, do DFS //If the adjacent node is unvisited, do DFS
if (insertionTime[n] == -1) { if (insertionTime[vertex] == -1) {
stronglyConnCompsUtil(n, lowTime, insertionTime, isInStack, st, graph); stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph);
//update lowTime for the current node comparing lowtime of adj node //update lowTime for the current node comparing lowtime of adj node
lowTime[u] = Math.min(lowTime[u], lowTime[n]); lowTime[u] = Math.min(lowTime[u], lowTime[vertex]);
} else if (isInStack[n]) { } else if (isInStack[vertex]) {
//If adj node is in stack, update low //If adj node is in stack, update low
lowTime[u] = Math.min(lowTime[u], insertionTime[n]); lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]);
} }
} }
//If lowtime and insertion time are same, current node is the head of an SCC //If lowtime and insertion time are same, current node is the head of an SCC

View File

@ -133,7 +133,7 @@ class Link {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
DoublyLinkedList myList = new DoublyLinkedList(); DoublyLinkedList myList = new DoublyLinkedList();
LinkOperations linkOperations = new LinkOperations(); LinkOperations linkOperations = new LinkOperations();
linkOperations.insertHead(13, myList); linkOperations.insertHead(13, myList);

View File

@ -39,8 +39,8 @@ public class MaximumMinimumWindow {
*/ */
public static int[] calculateMaxOfMin(int[] arr, int n) { public static int[] calculateMaxOfMin(int[] arr, int n) {
Stack<Integer> s = new Stack<>(); Stack<Integer> s = new Stack<>();
int left[] = new int[n + 1]; int[] left = new int[n + 1];
int right[] = new int[n + 1]; int[] right = new int[n + 1];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
left[i] = -1; left[i] = -1;
right[i] = n; right[i] = n;
@ -74,7 +74,7 @@ public class MaximumMinimumWindow {
s.push(i); s.push(i);
} }
int ans[] = new int[n + 1]; int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) { for (int i = 0; i <= n; i++) {
ans[i] = 0; ans[i] = 0;
} }
@ -96,7 +96,7 @@ public class MaximumMinimumWindow {
return ans; return ans;
} }
public static void main(String args[]) { public static void main(String[] args) {
int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 }; int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 }; int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
int[] res = calculateMaxOfMin(arr, arr.length); int[] res = calculateMaxOfMin(arr, arr.length);

View File

@ -118,7 +118,7 @@ public class PostfixToInfix {
return infix; return infix;
} }
public static void main(String args[]) { public static void main(String[] args) {
assert getPostfixToInfix("ABC+/").equals("(A/(B+C))"); assert getPostfixToInfix("ABC+/").equals("(A/(B+C))");
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))"); assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)"); assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");

View File

@ -10,7 +10,7 @@ import java.util.Stack;
*/ */
public class ReverseStack { public class ReverseStack {
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println( System.out.println(
"Enter the number of elements you wish to insert in the stack" "Enter the number of elements you wish to insert in the stack"

View File

@ -3,7 +3,7 @@ package com.thealgorithms.datastructures.trees;
public class FenwickTree { public class FenwickTree {
private int n; private int n;
private int fen_t[]; private int[] fen_t;
/* Constructor which takes the size of the array as a parameter */ /* Constructor which takes the size of the array as a parameter */
public FenwickTree(int n) { public FenwickTree(int n) {

View File

@ -2,12 +2,12 @@ package com.thealgorithms.datastructures.trees;
public class SegmentTree { public class SegmentTree {
private int seg_t[]; private int[] seg_t;
private int n; private int n;
private int arr[]; private int[] arr;
/* Constructor which takes the size of the array and the array as a parameter*/ /* Constructor which takes the size of the array and the array as a parameter*/
public SegmentTree(int n, int arr[]) { public SegmentTree(int n, int[] arr) {
this.n = n; this.n = n;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int seg_size = 2 * (int) Math.pow(2, x) - 1; int seg_size = 2 * (int) Math.pow(2, x) - 1;

View File

@ -12,5 +12,5 @@ public interface MatrixSearchAlgorithm {
* @param <T> Comparable type * @param <T> Comparable type
* @return array containing the first found coordinates of the element * @return array containing the first found coordinates of the element
*/ */
<T extends Comparable<T>> int[] find(T matrix[][], T key); <T extends Comparable<T>> int[] find(T[][] matrix, T key);
} }

View File

@ -12,5 +12,5 @@ public interface SearchAlgorithm {
* @param <T> Comparable type * @param <T> Comparable type
* @return first found index of the element * @return first found index of the element
*/ */
<T extends Comparable<T>> int find(T array[], T key); <T extends Comparable<T>> int find(T[] array, T key);
} }

View File

@ -52,7 +52,7 @@ public class BoardPath {
return count; return count;
} }
public static int bpRS(int curr, int end, int strg[]) { public static int bpRS(int curr, int end, int[] strg) {
if (curr == end) { if (curr == end) {
return 1; return 1;
} else if (curr > end) { } else if (curr > end) {

View File

@ -6,7 +6,7 @@ public class BruteForceKnapsack {
// Returns the maximum value that // Returns the maximum value that
// can be put in a knapsack of // can be put in a knapsack of
// capacity W // capacity W
static int knapSack(int W, int wt[], int val[], int n) { static int knapSack(int W, int[] wt, int[] val, int n) {
// Base Case // Base Case
if (n == 0 || W == 0) { if (n == 0 || W == 0) {
return 0; return 0;
@ -29,9 +29,9 @@ public class BruteForceKnapsack {
} }
// Driver code // Driver code
public static void main(String args[]) { public static void main(String[] args) {
int val[] = new int[] { 60, 100, 120 }; int[] val = new int[] { 60, 100, 120 };
int wt[] = new int[] { 10, 20, 30 }; int[] wt = new int[] { 10, 20, 30 };
int W = 50; int W = 50;
int n = val.length; int n = val.length;
System.out.println(knapSack(W, wt, val, n)); System.out.println(knapSack(W, wt, val, n));

View File

@ -23,7 +23,7 @@ public class CatalanNumber {
*/ */
static long findNthCatalan(int n) { static long findNthCatalan(int n) {
// Array to store the results of subproblems i.e Catalan numbers from [1...n-1] // Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
long catalanArray[] = new long[n + 1]; long[] catalanArray = new long[n + 1];
// Initialising C₀ = 1 and C₁ = 1 // Initialising C₀ = 1 and C₁ = 1
catalanArray[0] = 1; catalanArray[0] = 1;

View File

@ -15,8 +15,8 @@ package com.thealgorithms.dynamicprogramming;
public class CountFriendsPairing { public class CountFriendsPairing {
public static boolean countFriendsPairing(int n, int a[]) { public static boolean countFriendsPairing(int n, int[] a) {
int dp[] = new int[n + 1]; int[] dp = new int[n + 1];
// array of n+1 size is created // array of n+1 size is created
dp[0] = 1; dp[0] = 1;
// since 1st index position value is fixed so it's marked as 1 // since 1st index position value is fixed so it's marked as 1

View File

@ -5,9 +5,9 @@ package com.thealgorithms.dynamicprogramming;
public class DyanamicProgrammingKnapsack { public class DyanamicProgrammingKnapsack {
// Returns the maximum value that can // Returns the maximum value that can
// be put in a knapsack of capacity W // be put in a knapsack of capacity W
static int knapSack(int W, int wt[], int val[], int n) { static int knapSack(int W, int[] wt, int[] val, int n) {
int i, w; int i, w;
int K[][] = new int[n + 1][W + 1]; int[][] K = new int[n + 1][W + 1];
// Build table K[][] in bottom up manner // Build table K[][] in bottom up manner
for (i = 0; i <= n; i++) { for (i = 0; i <= n; i++) {
@ -26,9 +26,9 @@ public class DyanamicProgrammingKnapsack {
} }
// Driver code // Driver code
public static void main(String args[]) { public static void main(String[] args) {
int val[] = new int[] { 60, 100, 120 }; int[] val = new int[] { 60, 100, 120 };
int wt[] = new int[] { 10, 20, 30 }; int[] wt = new int[] { 10, 20, 30 };
int W = 50; int W = 50;
int n = val.length; int n = val.length;
System.out.println(knapSack(W, wt, val, n)); System.out.println(knapSack(W, wt, val, n));

View File

@ -40,7 +40,7 @@ public class EggDropping {
return eggFloor[n][m]; return eggFloor[n][m];
} }
public static void main(String args[]) { public static void main(String[] args) {
int n = 2, m = 4; int n = 2, m = 4;
// result outputs min no. of trials in worst case for n eggs and m floors // result outputs min no. of trials in worst case for n eggs and m floors
int result = minTrials(n, m); int result = minTrials(n, m);

View File

@ -7,7 +7,7 @@ package com.thealgorithms.dynamicprogramming;
public class KadaneAlgorithm { public class KadaneAlgorithm {
public static boolean max_Sum(int a[], int predicted_answer) { public static boolean max_Sum(int[] a, int predicted_answer) {
int sum = a[0], running_sum = 0; int sum = a[0], running_sum = 0;
for (int k : a) { for (int k : a) {
running_sum = running_sum + k; running_sum = running_sum + k;

View File

@ -5,13 +5,13 @@ package com.thealgorithms.dynamicprogramming;
*/ */
public class Knapsack { public class Knapsack {
private static int knapSack(int W, int wt[], int val[], int n) private static int knapSack(int W, int[] wt, int[] val, int n)
throws IllegalArgumentException { throws IllegalArgumentException {
if (wt == null || val == null) { if (wt == null || val == null) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
int i, w; int i, w;
int rv[][] = new int[n + 1][W + 1]; // rv means return value int[][] rv = new int[n + 1][W + 1]; // rv means return value
// Build table rv[][] in bottom up manner // Build table rv[][] in bottom up manner
for (i = 0; i <= n; i++) { for (i = 0; i <= n; i++) {
@ -34,9 +34,9 @@ public class Knapsack {
} }
// Driver program to test above function // Driver program to test above function
public static void main(String args[]) { public static void main(String[] args) {
int val[] = new int[] { 50, 100, 130 }; int[] val = new int[] { 50, 100, 130 };
int wt[] = new int[] { 10, 20, 40 }; int[] wt = new int[] { 10, 20, 40 };
int W = 50; int W = 50;
System.out.println(knapSack(W, wt, val, val.length)); System.out.println(knapSack(W, wt, val, val.length));
} }

View File

@ -28,7 +28,6 @@ public class KnapsackMemoization {
int solveKnapsackRecursive(int capacity, int[] weights, int solveKnapsackRecursive(int capacity, int[] weights,
int[] profits, int numOfItems, int[] profits, int numOfItems,
int[][] dpTable) { int[][] dpTable) {
// Base condition // Base condition
if (numOfItems == 0 || capacity == 0) { if (numOfItems == 0 || capacity == 0) {
return 0; return 0;

View File

@ -13,7 +13,7 @@ package com.thealgorithms.dynamicprogramming;
public class LongestAlternatingSubsequence { public class LongestAlternatingSubsequence {
/* Function to return longest alternating subsequence length*/ /* Function to return longest alternating subsequence length*/
static int AlternatingLength(int arr[], int n) { static int AlternatingLength(int[] arr, int n) {
/* /*
las[i][0] = Length of the longest las[i][0] = Length of the longest
@ -28,7 +28,7 @@ public class LongestAlternatingSubsequence {
element element
*/ */
int las[][] = new int[n][2]; // las = LongestAlternatingSubsequence int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
las[i][0] = las[i][1] = 1; las[i][0] = las[i][1] = 1;
@ -61,7 +61,7 @@ public class LongestAlternatingSubsequence {
} }
public static void main(String[] args) { public static void main(String[] args) {
int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 };
int n = arr.length; int n = arr.length;
System.out.println( System.out.println(
"Length of Longest " + "Length of Longest " +

View File

@ -11,7 +11,7 @@ public class LongestIncreasingSubsequence {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); int n = sc.nextInt();
int arr[] = new int[n]; int[] arr = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); arr[i] = sc.nextInt();
} }
@ -70,9 +70,9 @@ public class LongestIncreasingSubsequence {
* @author Alon Firestein (https://github.com/alonfirestein) * @author Alon Firestein (https://github.com/alonfirestein)
*/ */
// A function for finding the length of the LIS algorithm in O(nlogn) complexity. // A function for finding the length of the LIS algorithm in O(nlogn) complexity.
public static int findLISLen(int a[]) { public static int findLISLen(int[] a) {
int size = a.length; int size = a.length;
int arr[] = new int[size]; int[] arr = new int[size];
arr[0] = a[0]; arr[0] = a[0];
int lis = 1; int lis = 1;
for (int i = 1; i < size; i++) { for (int i = 1; i < size; i++) {

View File

@ -20,7 +20,7 @@ public class LongestPalindromicSubstring {
if (input == null || input.length() == 0) { if (input == null || input.length() == 0) {
return input; return input;
} }
boolean arr[][] = new boolean[input.length()][input.length()]; boolean[][] arr = new boolean[input.length()][input.length()];
int start = 0, end = 0; int start = 0, end = 0;
for (int g = 0; g < input.length(); g++) { for (int g = 0; g < input.length(); g++) {
for (int i = 0, j = g; j < input.length(); i++, j++) { for (int i = 0, j = g; j < input.length(); i++, j++) {

View File

@ -8,9 +8,9 @@ package com.thealgorithms.dynamicprogramming;
// minimizes the number of scalar multiplications. // minimizes the number of scalar multiplications.
public class MatrixChainRecursiveTopDownMemoisation { public class MatrixChainRecursiveTopDownMemoisation {
static int Memoized_Matrix_Chain(int p[]) { static int Memoized_Matrix_Chain(int[] p) {
int n = p.length; int n = p.length;
int m[][] = new int[n][n]; int[][] m = new int[n][n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
m[i][j] = Integer.MAX_VALUE; m[i][j] = Integer.MAX_VALUE;
@ -19,7 +19,7 @@ public class MatrixChainRecursiveTopDownMemoisation {
return Lookup_Chain(m, p, 1, n - 1); return Lookup_Chain(m, p, 1, n - 1);
} }
static int Lookup_Chain(int m[][], int p[], int i, int j) { static int Lookup_Chain(int[][] m, int[] p, int i, int j) {
if (i == j) { if (i == j) {
m[i][j] = 0; m[i][j] = 0;
return m[i][j]; return m[i][j];
@ -43,7 +43,7 @@ public class MatrixChainRecursiveTopDownMemoisation {
// in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively
// output should be Minimum number of multiplications is 38 // output should be Minimum number of multiplications is 38
public static void main(String[] args) { public static void main(String[] args) {
int arr[] = { 1, 2, 3, 4, 5 }; int[] arr = { 1, 2, 3, 4, 5 };
System.out.println( System.out.println(
"Minimum number of multiplications is " + Memoized_Matrix_Chain(arr) "Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)
); );

View File

@ -10,7 +10,7 @@ package com.thealgorithms.dynamicprogramming;
public class NewManShanksPrime { public class NewManShanksPrime {
public static boolean nthManShanksPrime(int n, int expected_answer) { public static boolean nthManShanksPrime(int n, int expected_answer) {
int a[] = new int[n + 1]; int[] a = new int[n + 1];
// array of n+1 size is initialized // array of n+1 size is initialized
a[0] = a[1] = 1; a[0] = a[1] = 1;
// The 0th and 1st index position values are fixed. They are initialized as 1 // The 0th and 1st index position values are fixed. They are initialized as 1

View File

@ -134,7 +134,7 @@ public class RegexMatching {
// Method 4: Bottom-Up DP(Tabulation) // Method 4: Bottom-Up DP(Tabulation)
// Time Complexity=0(N*M) Space Complexity=0(N*M) // Time Complexity=0(N*M) Space Complexity=0(N*M)
static boolean regexBU(String src, String pat) { static boolean regexBU(String src, String pat) {
boolean strg[][] = new boolean[src.length() + 1][pat.length() + 1]; boolean[][] strg = new boolean[src.length() + 1][pat.length() + 1];
strg[src.length()][pat.length()] = true; strg[src.length()][pat.length()] = true;
for (int row = src.length(); row >= 0; row--) { for (int row = src.length(); row >= 0; row--) {
for (int col = pat.length() - 1; col >= 0; col--) { for (int col = pat.length() - 1; col >= 0; col--) {

View File

@ -8,7 +8,7 @@ package com.thealgorithms.dynamicprogramming;
public class RodCutting { public class RodCutting {
private static int cutRod(int[] price, int n) { private static int cutRod(int[] price, int n) {
int val[] = new int[n + 1]; int[] val = new int[n + 1];
val[0] = 0; val[0] = 0;
for (int i = 1; i <= n; i++) { for (int i = 1; i <= n; i++) {
@ -24,7 +24,7 @@ public class RodCutting {
} }
// main function to test // main function to test
public static void main(String args[]) { public static void main(String[] args) {
int[] arr = new int[] { 2, 5, 13, 19, 20 }; int[] arr = new int[] { 2, 5, 13, 19, 20 };
int result = cutRod(arr, arr.length); int result = cutRod(arr, arr.length);
System.out.println("Maximum Obtainable Value is " + result); System.out.println("Maximum Obtainable Value is " + result);

View File

@ -45,7 +45,7 @@ class ShortestSuperSequence {
} }
// Driver code // Driver code
public static void main(String args[]) { public static void main(String[] args) {
String X = "AGGTAB"; String X = "AGGTAB";
String Y = "GXTXAYB"; String Y = "GXTXAYB";

View File

@ -49,11 +49,11 @@ public class SubsetCount {
*/ */
public int getCountSO(int[] arr, int target){ public int getCountSO(int[] arr, int target){
int n = arr.length; int n = arr.length;
int prev[]=new int[target+1]; int[] prev =new int[target+1];
prev[0] =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++){ for(int ind = 1; ind<n; ind++){
int cur[]=new int[target+1]; int[] cur =new int[target+1];
cur[0]=1; cur[0]=1;
for(int t= 1; t<=target; t++){ for(int t= 1; t<=target; t++){
int notTaken = prev[t]; int notTaken = prev[t];

View File

@ -31,7 +31,7 @@ public class UniquePaths {
// The above method runs in O(n) time // The above method runs in O(n) time
public static boolean uniquePaths2(int m, int n, int ans) { public static boolean uniquePaths2(int m, int n, int ans) {
int dp[][] = new int[m][n]; int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) { for (int i = 0; i < m; i++) {
dp[i][0] = 1; dp[i][0] = 1;
} }

View File

@ -10,12 +10,12 @@ public class DeterminantOfMatrix {
// Determinant calculator // Determinant calculator
//@return determinant of the input matrix //@return determinant of the input matrix
static int determinant(int a[][], int n) { static int determinant(int[][] a, int n) {
int det = 0, sign = 1, p = 0, q = 0; int det = 0, sign = 1, p = 0, q = 0;
if (n == 1) { if (n == 1) {
det = a[0][0]; det = a[0][0];
} else { } else {
int b[][] = new int[n - 1][n - 1]; int[][] b = new int[n - 1][n - 1];
for (int x = 0; x < n; x++) { for (int x = 0; x < n; x++) {
p = 0; p = 0;
q = 0; q = 0;
@ -44,7 +44,7 @@ public class DeterminantOfMatrix {
System.out.println("Enter matrix size (Square matrix only)"); System.out.println("Enter matrix size (Square matrix only)");
int n = in.nextInt(); int n = in.nextInt();
System.out.println("Enter matrix"); System.out.println("Enter matrix");
int a[][] = new int[n][n]; int[][] a = new int[n][n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt(); a[i][j] = in.nextInt();

View File

@ -40,7 +40,7 @@ public class KrishnamurthyNumber {
} }
} }
public static void main(String args[]) throws IOException { public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader( BufferedReader br = new BufferedReader(
new InputStreamReader(System.in) new InputStreamReader(System.in)
); );

View File

@ -19,7 +19,7 @@ public class NonRepeatingElement {
System.out.println("Array should contain even number of elements"); System.out.println("Array should contain even number of elements");
return; return;
} }
int arr[] = new int[n]; int[] arr = new int[n];
System.out.println( System.out.println(
"Enter " + "Enter " +

View File

@ -39,7 +39,7 @@ public class TrinomialTriangle {
} }
} }
public static void main(String argc[]) { public static void main(String[] argc) {
int n = 6; int n = 6;
printTrinomial(n); printTrinomial(n);
} }

View File

@ -117,7 +117,7 @@ public class ColorContrastRatio {
4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio.";
} }
public static void main(String args[]) { public static void main(String[] args) {
test(); test();
} }
} }

View File

@ -12,11 +12,11 @@ import java.util.Scanner;
*/ */
public class InverseOfMatrix { public class InverseOfMatrix {
public static void main(String argv[]) { public static void main(String[] argv) {
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
System.out.println("Enter the matrix size (Square matrix only): "); System.out.println("Enter the matrix size (Square matrix only): ");
int n = input.nextInt(); int n = input.nextInt();
double a[][] = new double[n][n]; double[][] a = new double[n][n];
System.out.println("Enter the elements of matrix: "); System.out.println("Enter the elements of matrix: ");
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
@ -24,7 +24,7 @@ public class InverseOfMatrix {
} }
} }
double d[][] = invert(a); double[][] d = invert(a);
System.out.println(); System.out.println();
System.out.println("The inverse is: "); System.out.println("The inverse is: ");
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
@ -36,11 +36,11 @@ public class InverseOfMatrix {
input.close(); input.close();
} }
public static double[][] invert(double a[][]) { public static double[][] invert(double[][] a) {
int n = a.length; int n = a.length;
double x[][] = new double[n][n]; double[][] x = new double[n][n];
double b[][] = new double[n][n]; double[][] b = new double[n][n];
int index[] = new int[n]; int[] index = new int[n];
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
b[i][i] = 1; b[i][i] = 1;
} }
@ -73,9 +73,9 @@ public class InverseOfMatrix {
// Method to carry out the partial-pivoting Gaussian // Method to carry out the partial-pivoting Gaussian
// elimination. Here index[] stores pivoting order. // elimination. Here index[] stores pivoting order.
public static void gaussian(double a[][], int index[]) { public static void gaussian(double[][] a, int[] index) {
int n = index.length; int n = index.length;
double c[] = new double[n]; double[] c = new double[n];
// Initialize the index // Initialize the index
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {

View File

@ -44,7 +44,7 @@ public class MedianOfRunningArray {
*/ */
MedianOfRunningArray p = new MedianOfRunningArray(); MedianOfRunningArray p = new MedianOfRunningArray();
int arr[] = { 10, 7, 4, 9, 2, 3, 11, 17, 14 }; int[] arr = { 10, 7, 4, 9, 2, 3, 11, 17, 14 };
for (int i = 0; i < 9; i++) { for (int i = 0; i < 9; i++) {
p.insert(arr[i]); p.insert(arr[i]);
System.out.print(p.median() + " "); System.out.print(p.median() + " ");

View File

@ -13,10 +13,10 @@ import java.util.*;
*/ */
public class Sort012D { public class Sort012D {
public static void main(String args[]) { public static void main(String[] args) {
Scanner np = new Scanner(System.in); Scanner np = new Scanner(System.in);
int n = np.nextInt(); int n = np.nextInt();
int a[] = new int[n]; int[] a = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
a[i] = np.nextInt(); a[i] = np.nextInt();
} }

View File

@ -4,14 +4,14 @@ import java.util.*;
public class ThreeSumProblem { public class ThreeSumProblem {
public static void main(String args[]) { public static void main(String[] args) {
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);
System.out.print("Enter the target sum "); System.out.print("Enter the target sum ");
int ts = scan.nextInt(); int ts = scan.nextInt();
System.out.print("Enter the number of elements in the array "); System.out.print("Enter the number of elements in the array ");
int n = scan.nextInt(); int n = scan.nextInt();
System.out.println("Enter all your array elements:"); System.out.println("Enter all your array elements:");
int arr[] = new int[n]; int[] arr = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt(); arr[i] = scan.nextInt();
} }

View File

@ -5,14 +5,14 @@ import java.util.stream.Collectors;
public class TwoSumProblem { public class TwoSumProblem {
public static void main(String args[]) { public static void main(String[] args) {
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);
System.out.print("Enter the target sum "); System.out.print("Enter the target sum ");
int ts = scan.nextInt(); int ts = scan.nextInt();
System.out.print("Enter the number of elements in the array "); System.out.print("Enter the number of elements in the array ");
int n = scan.nextInt(); int n = scan.nextInt();
System.out.println("Enter all your array elements:"); System.out.println("Enter all your array elements:");
int arr[] = new int[n]; int[] arr = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt(); arr[i] = scan.nextInt();
} }
@ -34,7 +34,7 @@ public class TwoSumProblem {
public int[] BruteForce(int[] nums, int target) { public int[] BruteForce(int[] nums, int target) {
//Brute Force Approach //Brute Force Approach
int ans[] = new int[2]; int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) { for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) { for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) { if (nums[i] + nums[j] == target) {
@ -51,7 +51,7 @@ public class TwoSumProblem {
public int[] TwoPointer(int[] nums, int target) { public int[] TwoPointer(int[] nums, int target) {
// HashMap Approach // HashMap Approach
int ans[] = new int[2]; int[] ans = new int[2];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) { for (int i = 0; i < nums.length; i++) {
hm.put(i, nums[i]); hm.put(i, nums[i]);
@ -90,7 +90,7 @@ public class TwoSumProblem {
public int[] HashMap(int[] nums, int target) { public int[] HashMap(int[] nums, int target) {
//Using Hashmaps //Using Hashmaps
int ans[] = new int[2]; int[] ans = new int[2];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) { for (int i = 0; i < nums.length; i++) {
hm.put(nums[i], i); hm.put(nums[i], i);

View File

@ -26,9 +26,9 @@ public class BankersAlgorithm {
* This method finds the need of each process * This method finds the need of each process
*/ */
static void calculateNeed( static void calculateNeed(
int needArray[][], int[][] needArray,
int maxArray[][], int[][] maxArray,
int allocationArray[][], int[][] allocationArray,
int totalProcess, int totalProcess,
int totalResources int totalResources
) { ) {
@ -55,10 +55,10 @@ public class BankersAlgorithm {
* @return boolean if the system is in safe state or not * @return boolean if the system is in safe state or not
*/ */
static boolean checkSafeSystem( static boolean checkSafeSystem(
int processes[], int[] processes,
int availableArray[], int[] availableArray,
int maxArray[][], int[][] maxArray,
int allocationArray[][], int[][] allocationArray,
int totalProcess, int totalProcess,
int totalResources int totalResources
) { ) {
@ -144,14 +144,14 @@ public class BankersAlgorithm {
System.out.println("Enter total number of resources"); System.out.println("Enter total number of resources");
numberOfResources = sc.nextInt(); numberOfResources = sc.nextInt();
int processes[] = new int[numberOfProcesses]; int[] processes = new int[numberOfProcesses];
for (int i = 0; i < numberOfProcesses; i++) { for (int i = 0; i < numberOfProcesses; i++) {
processes[i] = i; processes[i] = i;
} }
System.out.println("--Enter the availability of--"); System.out.println("--Enter the availability of--");
int availableArray[] = new int[numberOfResources]; int[] availableArray = new int[numberOfResources];
for (int i = 0; i < numberOfResources; i++) { for (int i = 0; i < numberOfResources; i++) {
System.out.println("resource " + i + ": "); System.out.println("resource " + i + ": ");
availableArray[i] = sc.nextInt(); availableArray[i] = sc.nextInt();
@ -159,7 +159,7 @@ public class BankersAlgorithm {
System.out.println("--Enter the maximum matrix--"); System.out.println("--Enter the maximum matrix--");
int maxArray[][] = new int[numberOfProcesses][numberOfResources]; int[][] maxArray = new int[numberOfProcesses][numberOfResources];
for (int i = 0; i < numberOfProcesses; i++) { for (int i = 0; i < numberOfProcesses; i++) {
System.out.println("For process " + i + ": "); System.out.println("For process " + i + ": ");
for (int j = 0; j < numberOfResources; j++) { for (int j = 0; j < numberOfResources; j++) {
@ -172,7 +172,7 @@ public class BankersAlgorithm {
System.out.println("--Enter the allocation matrix--"); System.out.println("--Enter the allocation matrix--");
int allocationArray[][] = new int[numberOfProcesses][numberOfResources]; int[][] allocationArray = new int[numberOfProcesses][numberOfResources];
for (int i = 0; i < numberOfProcesses; i++) { for (int i = 0; i < numberOfProcesses; i++) {
System.out.println("For process " + i + ": "); System.out.println("For process " + i + ": ");
for (int j = 0; j < numberOfResources; j++) { for (int j = 0; j < numberOfResources; j++) {

View File

@ -35,10 +35,10 @@ public class BoyerMoore {
return -1; return -1;
} }
public static void main(String args[]) { public static void main(String[] args) {
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
int n = input.nextInt(); int n = input.nextInt();
int a[] = new int[n]; int[] a = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
a[i] = input.nextInt(); a[i] = input.nextInt();
} }

View File

@ -38,7 +38,7 @@ public class BrianKernighanAlgorithm {
/** /**
* @param args : command line arguments * @param args : command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); int num = sc.nextInt();
int setBitCount = countSetBits(num); int setBitCount = countSetBits(num);

View File

@ -158,9 +158,7 @@ public class CRCAlgorithm {
} }
dividedMessage = (ArrayList<Integer>) x.clone(); dividedMessage = (ArrayList<Integer>) x.clone();
if (!check) { if (!check) {
for (int z : dividedMessage) { message.addAll(dividedMessage);
message.add(z);
}
} else { } else {
if (dividedMessage.contains(1) && messageChanged) { if (dividedMessage.contains(1) && messageChanged) {
wrongMessCaught++; wrongMessCaught++;

View File

@ -21,7 +21,7 @@ public class GuassLegendre {
double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
for (int i = 0; i < l; ++i) { for (int i = 0; i < l; ++i) {
double temp[] = update(a, b, t, p); double[] temp = update(a, b, t, p);
a = temp[0]; a = temp[0];
b = temp[1]; b = temp[1];
t = temp[2]; t = temp[2];
@ -32,7 +32,7 @@ public class GuassLegendre {
} }
static double[] update(double a, double b, double t, double p) { static double[] update(double a, double b, double t, double p) {
double values[] = new double[4]; double[] values = new double[4];
values[0] = (a + b) / 2; values[0] = (a + b) / 2;
values[1] = Math.sqrt(a * b); values[1] = Math.sqrt(a * b);
values[2] = t - p * Math.pow(a - values[0], 2); values[2] = t - p * Math.pow(a - values[0], 2);

View File

@ -10,7 +10,7 @@ class Trieac {
// Trie node // Trie node
static class TrieNode { static class TrieNode {
TrieNode children[] = new TrieNode[ALPHABET_SIZE]; TrieNode[] children = new TrieNode[ALPHABET_SIZE];
// isWordEnd is true if the node represents // isWordEnd is true if the node represents
// end of a word // end of a word

View File

@ -8,7 +8,7 @@ public class InsertDeleteInArray {
Scanner s = new Scanner(System.in); // Input statement Scanner s = new Scanner(System.in); // Input statement
System.out.println("Enter the size of the array"); System.out.println("Enter the size of the array");
int size = s.nextInt(); int size = s.nextInt();
int a[] = new int[size]; int[] a = new int[size];
int i; int i;
// To enter the initial elements // To enter the initial elements
@ -25,7 +25,7 @@ public class InsertDeleteInArray {
System.out.println("Enter the element to be inserted"); System.out.println("Enter the element to be inserted");
int ins = s.nextInt(); int ins = s.nextInt();
int size2 = size + 1; int size2 = size + 1;
int b[] = new int[size2]; int[] b = new int[size2];
for (i = 0; i < size2; i++) { for (i = 0; i < size2; i++) {
if (i <= insert_pos) { if (i <= insert_pos) {
b[i] = a[i]; b[i] = a[i];

View File

@ -12,7 +12,7 @@ class Krishnamurthy {
return p; return p;
} }
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int a, b, s = 0; int a, b, s = 0;
System.out.print("Enter the number : "); System.out.print("Enter the number : ");

View File

@ -4,7 +4,7 @@ import java.util.*;
class PageRank { class PageRank {
public static void main(String args[]) { public static void main(String[] args) {
int nodes, i, j; int nodes, i, j;
Scanner in = new Scanner(System.in); Scanner in = new Scanner(System.in);
System.out.print("Enter the Number of WebPages: "); System.out.print("Enter the Number of WebPages: ");
@ -24,14 +24,14 @@ class PageRank {
p.calc(nodes); p.calc(nodes);
} }
public int path[][] = new int[10][10]; public int[][] path = new int[10][10];
public double pagerank[] = new double[10]; public double[] pagerank = new double[10];
public void calc(double totalNodes) { public void calc(double totalNodes) {
double InitialPageRank; double InitialPageRank;
double OutgoingLinks = 0; double OutgoingLinks = 0;
double DampingFactor = 0.85; double DampingFactor = 0.85;
double TempPageRank[] = new double[10]; double[] TempPageRank = new double[10];
int ExternalNodeNumber; int ExternalNodeNumber;
int InternalNodeNumber; int InternalNodeNumber;
int k = 1; // For Traversing int k = 1; // For Traversing

View File

@ -13,7 +13,7 @@ import java.util.Random;
*/ */
class PasswordGen { class PasswordGen {
public static void main(String args[]) { public static void main(String[] args) {
String password = generatePassword(8, 16); String password = generatePassword(8, 16);
System.out.print("Password: " + password); System.out.print("Password: " + password);
} }

View File

@ -119,7 +119,7 @@ public class QueueUsingTwoStacks {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
QueueWithStack myQueue = new QueueWithStack(); QueueWithStack myQueue = new QueueWithStack();
myQueue.insert(1); myQueue.insert(1);
System.out.println(myQueue.peekBack()); // Will print 1 System.out.println(myQueue.peekBack()); // Will print 1

View File

@ -29,7 +29,7 @@ class Rotate_by_90_degree {
sc.close(); sc.close();
} }
static void printMatrix(int arr[][]) { static void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) { for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) { for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " "); System.out.print(arr[i][j] + " ");
@ -44,7 +44,7 @@ class Rotate_by_90_degree {
*/ */
class Rotate { class Rotate {
static void rotate(int a[][]) { static void rotate(int[][] a) {
int n = a.length; int n = a.length;
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {

View File

@ -24,14 +24,11 @@ public class StackPostfixNotation {
int num1 = s.pop(); int num1 = s.pop();
String op = tokens.next(); String op = tokens.next();
if (op.equals("+")) { switch (op) {
s.push(num1 + num2); case "+" -> s.push(num1 + num2);
} else if (op.equals("-")) { case "-" -> s.push(num1 - num2);
s.push(num1 - num2); case "*" -> s.push(num1 * num2);
} else if (op.equals("*")) { default -> s.push(num1 / num2);
s.push(num1 * num2);
} else {
s.push(num1 / num2);
} }
// "+", "-", "*", "/" // "+", "-", "*", "/"
} }

View File

@ -100,7 +100,7 @@ class Sudoku {
} }
// Driver Code // Driver Code
public static void main(String args[]) { public static void main(String[] args) {
int[][] board = new int[][] { int[][] board = new int[][] {
{ 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 },

View File

@ -18,11 +18,11 @@ import java.util.Scanner;
*/ */
class ThreeSum { class ThreeSum {
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Length of an array int n = sc.nextInt(); // Length of an array
int a[] = new int[n]; int[] a = new int[n];
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
a[i] = sc.nextInt(); a[i] = sc.nextInt();

View File

@ -42,7 +42,7 @@ class BinarySearch implements SearchAlgorithm {
* @return the location of the key * @return the location of the key
*/ */
private <T extends Comparable<T>> int search( private <T extends Comparable<T>> int search(
T array[], T[] array,
T key, T key,
int left, int left,
int right int right

View File

@ -21,7 +21,7 @@ class InterpolationSearch {
* @param key is a value what shoulb be found in the array * @param key is a value what shoulb be found in the array
* @return an index if the array contains the key unless -1 * @return an index if the array contains the key unless -1
*/ */
public int find(int array[], int key) { public int find(int[] array, int key) {
// Find indexes of two corners // Find indexes of two corners
int start = 0, end = (array.length - 1); int start = 0, end = (array.length - 1);

View File

@ -8,7 +8,7 @@ class KMPSearch {
// create lps[] that will hold the longest // create lps[] that will hold the longest
// prefix suffix values for pattern // prefix suffix values for pattern
int lps[] = new int[M]; int[] lps = new int[M];
int j = 0; // index for pat[] int j = 0; // index for pat[]
// Preprocess the pattern (calculate lps[] // Preprocess the pattern (calculate lps[]
@ -38,7 +38,7 @@ class KMPSearch {
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 // length of the previous longest prefix suffix
int len = 0; int len = 0;
int i = 1; int i = 1;

View File

@ -13,7 +13,7 @@ package com.thealgorithms.searches;
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 // Checking whether the given array is ascending order
boolean AscOrd = arr[start] < arr[end]; boolean AscOrd = arr[start] < arr[end];

View File

@ -28,9 +28,9 @@ public class SaddlebackSearch {
* @return The index(row and column) of the element if found. Else returns * @return The index(row and column) of the element if found. Else returns
* -1 -1. * -1 -1.
*/ */
private static int[] find(int arr[][], int row, int col, int key) { private static int[] find(int[][] arr, int row, int col, int key) {
// array to store the answer row and column // array to store the answer row and column
int ans[] = { -1, -1 }; int[] ans = { -1, -1 };
if (row < 0 || col >= arr[row].length) { if (row < 0 || col >= arr[row].length) {
return ans; return ans;
} }
@ -54,7 +54,7 @@ public class SaddlebackSearch {
public static void main(String[] args) { public static void main(String[] args) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
int arr[][]; int[][] arr;
int i, j, rows = sc.nextInt(), col = sc.nextInt(); int i, j, rows = sc.nextInt(), col = sc.nextInt();
arr = new int[rows][col]; arr = new int[rows][col];
for (i = 0; i < rows; i++) { for (i = 0; i < rows; i++) {
@ -64,7 +64,7 @@ public class SaddlebackSearch {
} }
int ele = sc.nextInt(); int ele = sc.nextInt();
// we start from bottom left corner // we start from bottom left corner
int ans[] = find(arr, rows - 1, 0, ele); int[] ans = find(arr, rows - 1, 0, ele);
System.out.println(ans[0] + " " + ans[1]); System.out.println(ans[0] + " " + ans[1]);
sc.close(); sc.close();
} }

View File

@ -21,7 +21,7 @@ public class SquareRootBinarySearch {
* *
* @param args Command line arguments * @param args Command line arguments
*/ */
public static void main(String args[]) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.print( System.out.print(
"Enter a number you want to calculate square root of : " "Enter a number you want to calculate square root of : "

View File

@ -1,7 +1,7 @@
package com.thealgorithms.searches; package com.thealgorithms.searches;
import java.util.*; import java.util.*;
public class sortOrderAgnosticBinarySearch { public class sortOrderAgnosticBinarySearch {
public static int find(int arr[],int key){ public static int find(int[] arr, int key){
int start = 0; int start = 0;
int end = arr.length-1; int end = arr.length-1;
boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order. boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order.

View File

@ -8,7 +8,7 @@ public class BitonicSort {
ASCENDING or DESCENDING; if (a[i] > a[j]) agrees ASCENDING or DESCENDING; if (a[i] > a[j]) agrees
with the direction, then a[i] and a[j] are with the direction, then a[i] and a[j] are
interchanged. */ interchanged. */
void compAndSwap(int a[], int i, int j, int dir) { void compAndSwap(int[] a, int i, int j, int dir) {
if ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { if ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) {
// Swapping elements // Swapping elements
int temp = a[i]; int temp = a[i];
@ -22,7 +22,7 @@ public class BitonicSort {
(means dir=0). The sequence to be sorted starts at (means dir=0). The sequence to be sorted starts at
index position low, the parameter cnt is the number index position low, the parameter cnt is the number
of elements to be sorted.*/ of elements to be sorted.*/
void bitonicMerge(int a[], int low, int cnt, int dir) { void bitonicMerge(int[] a, int low, int cnt, int dir) {
if (cnt > 1) { if (cnt > 1) {
int k = cnt / 2; int k = cnt / 2;
for (int i = low; i < low + k; i++) { for (int i = low; i < low + k; i++) {
@ -37,7 +37,7 @@ public class BitonicSort {
recursively sorting its two halves in opposite sorting recursively sorting its two halves in opposite sorting
orders, and then calls bitonicMerge to make them in orders, and then calls bitonicMerge to make them in
the same order */ the same order */
void bitonicSort(int a[], int low, int cnt, int dir) { void bitonicSort(int[] a, int low, int cnt, int dir) {
if (cnt > 1) { if (cnt > 1) {
int k = cnt / 2; int k = cnt / 2;
@ -55,12 +55,12 @@ public class BitonicSort {
/*Caller of bitonicSort for sorting the entire array /*Caller of bitonicSort for sorting the entire array
of length N in ASCENDING order */ of length N in ASCENDING order */
void sort(int a[], int N, int up) { void sort(int[] a, int N, int up) {
bitonicSort(a, 0, N, up); bitonicSort(a, 0, N, up);
} }
/* A utility function to print array of size n */ /* A utility function to print array of size n */
static void printArray(int arr[]) { static void printArray(int[] arr) {
int n = arr.length; int n = arr.length;
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " "); System.out.print(arr[i] + " ");
@ -68,8 +68,8 @@ public class BitonicSort {
System.out.println(); System.out.println();
} }
public static void main(String args[]) { public static void main(String[] args) {
int a[] = { 3, 7, 4, 8, 6, 2, 1, 5 }; int[] a = { 3, 7, 4, 8, 6, 2, 1, 5 };
int up = 1; int up = 1;
BitonicSort ob = new BitonicSort(); BitonicSort ob = new BitonicSort();
ob.sort(a, a.length, up); ob.sort(a, a.length, up);

View File

@ -74,7 +74,7 @@ class CycleSort implements SortAlgorithm {
} }
public static void main(String[] args) { public static void main(String[] args) {
Integer arr[] = { Integer[] arr = {
4, 4,
23, 23,
6, 6,

View File

@ -4,7 +4,7 @@ public class DNFSort {
// Sort the input array, the array is assumed to // Sort the input array, the array is assumed to
// have values in {0, 1, 2} // have values in {0, 1, 2}
static void sort012(int a[], int arr_size) { static void sort012(int[] a, int arr_size) {
int low = 0; int low = 0;
int high = arr_size - 1; int high = arr_size - 1;
int mid = 0, temp = 0; int mid = 0, temp = 0;
@ -35,7 +35,7 @@ public class DNFSort {
} }
/* Utility function to print array arr[] */ /* Utility function to print array arr[] */
static void printArray(int arr[], int arr_size) { static void printArray(int[] arr, int arr_size) {
for (int i = 0; i < arr_size; i++) { for (int i = 0; i < arr_size; i++) {
System.out.print(arr[i] + " "); System.out.print(arr[i] + " ");
} }
@ -44,7 +44,7 @@ public class DNFSort {
/*Driver function to check for above functions*/ /*Driver function to check for above functions*/
public static void main(String[] args) { public static void main(String[] args) {
int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int[] arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
int arr_size = arr.length; int arr_size = arr.length;
sort012(arr, arr_size); sort012(arr, arr_size);
System.out.println("Array after seggregation "); System.out.println("Array after seggregation ");

View File

@ -96,7 +96,7 @@ public class DualPivotQuickSort implements SortAlgorithm {
* @param args the command line arguments * @param args the command line arguments
*/ */
public static void main(String[] args) { public static void main(String[] args) {
Integer array[] = { 24, 8, -42, 75, -29, -77, 38, 57 }; Integer[] array = { 24, 8, -42, 75, -29, -77, 38, 57 };
DualPivotQuickSort dualPivotQuickSort = new DualPivotQuickSort(); DualPivotQuickSort dualPivotQuickSort = new DualPivotQuickSort();
dualPivotQuickSort.sort(array); dualPivotQuickSort.sort(array);
for (int i = 0; i < array.length; i++) { for (int i = 0; i < array.length; i++) {

View File

@ -10,12 +10,12 @@ import java.util.*;
public class LinkListSort { public class LinkListSort {
public static boolean isSorted(int p[], int option) { public static boolean isSorted(int[] p, int option) {
try (Scanner sc = new Scanner(System.in)) { try (Scanner sc = new Scanner(System.in)) {
} }
int a[] = p; int[] a = p;
// Array is taken as input from test class // Array is taken as input from test class
int b[] = p; int[] b = p;
// array similar to a // array similar to a
int ch = option; int ch = option;
// Choice is choosed as any number from 1 to 3 (So the linked list will be // Choice is choosed as any number from 1 to 3 (So the linked list will be
@ -106,7 +106,7 @@ public class LinkListSort {
return false; return false;
} }
boolean compare(int a[], int b[]) { boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) if (a[i] != b[i])
return false; return false;
@ -137,7 +137,7 @@ class Node {
class Task { class Task {
static int a[]; static int[] a;
public Node sortByMergeSort(Node head) { public Node sortByMergeSort(Node head) {
if (head == null || head.next == null) if (head == null || head.next == null)
@ -171,7 +171,7 @@ class Task {
// It will return a integer type value denoting the number of nodes present // It will return a integer type value denoting the number of nodes present
} }
void task(int n[], int i, int j) { void task(int[] n, int i, int j) {
if (i < j) { if (i < j) {
int m = (i + j) / 2; int m = (i + j) / 2;
task(n, i, m); task(n, i, m);
@ -181,9 +181,9 @@ class Task {
} }
} }
void task1(int n[], int s, int m, int e) { void task1(int[] n, int s, int m, int e) {
int i = s, k = 0, j = m + 1; int i = s, k = 0, j = m + 1;
int b[] = new int[e - s + 1]; int[] b = new int[e - s + 1];
while (i <= m && j <= e) { while (i <= m && j <= e) {
if (n[j] >= n[i]) if (n[j] >= n[i])
b[k++] = n[i++]; b[k++] = n[i++];
@ -210,7 +210,7 @@ class Task1 {
if (head == null || head.next == null) if (head == null || head.next == null)
return head; return head;
int c = count(head); int c = count(head);
int a[] = new int[c]; int[] a = new int[c];
// Array of size c is created // Array of size c is created
a[0] = head.val; a[0] = head.val;
int i; int i;
@ -247,7 +247,7 @@ class Task1 {
class Task2 { class Task2 {
static int a[]; static int[] a;
public Node sortByHeapSort(Node head) { public Node sortByHeapSort(Node head) {
if (head == null || head.next == null) if (head == null || head.next == null)
@ -280,7 +280,7 @@ class Task2 {
// It will return a integer type value denoting the number of nodes present // It will return a integer type value denoting the number of nodes present
} }
void task(int n[]) { void task(int[] n) {
int k = n.length; int k = n.length;
for (int i = k / 2 - 1; i >= 0; i--) { for (int i = k / 2 - 1; i >= 0; i--) {
task1(n, k, i); task1(n, k, i);
@ -294,7 +294,7 @@ class Task2 {
} }
} }
void task1(int n[], int k, int i) { void task1(int[] n, int k, int i) {
int p = i; int p = i;
int l = 2 * i + 1; int l = 2 * i + 1;
int r = 2 * i + 2; int r = 2 * i + 2;

View File

@ -8,12 +8,12 @@ For understanding about mergesort visit :https://www.geeksforgeeks.org/merge-sor
*/ */
public class MergeSortNoExtraSpace { public class MergeSortNoExtraSpace {
public static void call_merge_sort(int a[], int n) { public static void call_merge_sort(int[] a, int n) {
int maxele = Arrays.stream(a).max().getAsInt() + 1; int maxele = Arrays.stream(a).max().getAsInt() + 1;
merge_sort(a, 0, n - 1, maxele); merge_sort(a, 0, n - 1, maxele);
} }
public static void merge_sort(int a[], int start, int end, int maxele) { //this function divides the array into 2 halves public static void merge_sort(int[] a, int start, int end, int maxele) { //this function divides the array into 2 halves
if (start < end) { if (start < end) {
int mid = (start + end) / 2; int mid = (start + end) / 2;
merge_sort(a, start, mid, maxele); merge_sort(a, start, mid, maxele);
@ -23,7 +23,7 @@ public class MergeSortNoExtraSpace {
} }
public static void implement_merge_sort( public static void implement_merge_sort(
int a[], int[] a,
int start, int start,
int mid, int mid,
int end, int end,
@ -58,11 +58,11 @@ public class MergeSortNoExtraSpace {
} }
} }
public static void main(String args[]) { public static void main(String[] args) {
Scanner inp = new Scanner(System.in); Scanner inp = new Scanner(System.in);
System.out.println("Enter array size"); System.out.println("Enter array size");
int n = inp.nextInt(); int n = inp.nextInt();
int a[] = new int[n]; int[] a = new int[n];
System.out.println("Enter array elements"); System.out.println("Enter array elements");
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
a[i] = inp.nextInt(); a[i] = inp.nextInt();

View File

@ -50,8 +50,8 @@ public class Anagrams {
if (s.length() != t.length()) { if (s.length() != t.length()) {
return false; return false;
} else { } else {
char c[] = s.toCharArray(); char[] c = s.toCharArray();
char d[] = t.toCharArray(); char[] d = t.toCharArray();
Arrays.sort(c); Arrays.sort(c);
Arrays.sort( Arrays.sort(
d d
@ -65,8 +65,8 @@ public class Anagrams {
if (a.length() != b.length()) { if (a.length() != b.length()) {
return false; return false;
} else { } else {
int m[] = new int[26]; int[] m = new int[26];
int n[] = new int[26]; int[] n = new int[26];
for (char c : a.toCharArray()) { for (char c : a.toCharArray()) {
m[c - 'a']++; m[c - 'a']++;
} }
@ -90,8 +90,8 @@ public class Anagrams {
} }
// this is similar to approach number 2 but here the string is not converted to character array // this is similar to approach number 2 but here the string is not converted to character array
else { else {
int a[] = new int[26]; int[] a = new int[26];
int b[] = new int[26]; int[] b = new int[26];
int k = s.length(); int k = s.length();
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
a[s.charAt(i) - 'a']++; a[s.charAt(i) - 'a']++;

View File

@ -44,7 +44,7 @@ public class LetterCombinationsOfPhoneNumber {
// Driver code // Driver code
public static void main(String[] args) { public static void main(String[] args) {
int number[] = { 2, 3, 4 }; int[] number = { 2, 3, 4 };
printWords(number); printWords(number);
} }
} }

View File

@ -22,18 +22,8 @@ public static int myAtoi(String s) {
number = "0"; number = "0";
break; break;
} }
switch (ch) { if(ch >= '0' && ch <= '9')
case '0' -> number += ch; number += ch;
case '1' -> number += ch;
case '2' -> number += ch;
case '3' -> number += ch;
case '4' -> number += ch;
case '5' -> number += ch;
case '6' -> number += ch;
case '7' -> number += ch;
case '8' -> number += ch;
case '9' -> number += ch;
}
} else if (ch == '-' && !isDigit) { } else if (ch == '-' && !isDigit) {
number += "0"; number += "0";
negative = true; negative = true;

View File

@ -48,10 +48,7 @@ class WordLadder {
* if the endword is there. Otherwise, will return the length as 0. * if the endword is there. Otherwise, will return the length as 0.
*/ */
public static int ladderLength(String beginWord, String endWord, List<String> wordList) { public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashSet<String> set = new HashSet(); HashSet<String> set = new HashSet(wordList);
for (String word : wordList) {
set.add(word);
}
if (!set.contains(endWord)) { if (!set.contains(endWord)) {
return 0; return 0;

View File

@ -9,7 +9,7 @@ public class AllPathsFromSourceToTargetTest {
@Test @Test
void testForFirstCase() { void testForFirstCase() {
int vertices = 4; int vertices = 4;
int a[][] = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}}; int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}};
int source = 2; int source = 2;
int destination = 3; int destination = 3;
List<List<Integer>> list2 = List.of(List.of(2, 0, 1, 3),List.of(2, 0, 3),List.of(2, 1, 3)); List<List<Integer>> list2 = List.of(List.of(2, 0, 1, 3),List.of(2, 0, 3),List.of(2, 1, 3));
@ -21,7 +21,7 @@ public class AllPathsFromSourceToTargetTest {
@Test @Test
void testForSecondCase() { void testForSecondCase() {
int vertices = 5; int vertices = 5;
int a[][] = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}}; int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}};
int source = 0; int source = 0;
int destination = 4; int destination = 4;
List<List<Integer>> list2 = List.of(List.of(0, 1, 3, 4),List.of(0, 1, 4),List.of(0, 2, 1, 3, 4),List.of(0, 2, 1, 4),List.of(0, 2, 4),List.of(0, 3, 4)); List<List<Integer>> list2 = List.of(List.of(0, 1, 3, 4),List.of(0, 1, 4),List.of(0, 2, 1, 3, 4),List.of(0, 2, 1, 4),List.of(0, 2, 4),List.of(0, 3, 4));
@ -33,7 +33,7 @@ public class AllPathsFromSourceToTargetTest {
@Test @Test
void testForThirdCase() { void testForThirdCase() {
int vertices = 6; int vertices = 6;
int a[][] = {{1,0},{2,3},{0,4},{1,5},{4,3},{0,2},{0,3},{1,2},{0,5},{3,4},{2,5},{2,4}}; int[][] a = {{1,0},{2,3},{0,4},{1,5},{4,3},{0,2},{0,3},{1,2},{0,5},{3,4},{2,5},{2,4}};
int source = 1; int source = 1;
int destination = 5; int destination = 5;
List<List<Integer>> list2 = List.of(List.of(1, 0, 2, 5),List.of(1, 0, 5),List.of(1, 5),List.of(1, 2, 5)); List<List<Integer>> list2 = List.of(List.of(1, 0, 2, 5),List.of(1, 0, 5),List.of(1, 5),List.of(1, 2, 5));
@ -45,7 +45,7 @@ public class AllPathsFromSourceToTargetTest {
@Test @Test
void testForFourthcase() { void testForFourthcase() {
int vertices = 3; int vertices = 3;
int a[][] = {{0,1},{0,2},{1,2}}; int[][] a = {{0,1},{0,2},{1,2}};
int source = 0; int source = 0;
int destination = 2; int destination = 2;
List<List<Integer>> list2 = List.of(List.of(0, 1, 2),List.of(0, 2)); List<List<Integer>> list2 = List.of(List.of(0, 1, 2),List.of(0, 2));

View File

@ -8,8 +8,8 @@ class FloodFillTest {
@Test @Test
void testForEmptyImage() { void testForEmptyImage() {
int image[][] = {}; int[][] image = {};
int expected[][] = {}; int[][] expected = {};
FloodFill.floodFill(image, 4, 5, 3, 2); FloodFill.floodFill(image, 4, 5, 3, 2);
assertArrayEquals(expected, image); assertArrayEquals(expected, image);
@ -17,8 +17,8 @@ class FloodFillTest {
@Test @Test
void testForSingleElementImage() { void testForSingleElementImage() {
int image[][] = { { 1 } }; int[][] image = { { 1 } };
int expected[][] = { { 3 } }; int[][] expected = { { 3 } };
FloodFill.floodFill(image, 0, 0, 3, 1); FloodFill.floodFill(image, 0, 0, 3, 1);
assertArrayEquals(expected, image); assertArrayEquals(expected, image);
@ -26,7 +26,7 @@ class FloodFillTest {
@Test @Test
void testForImageOne() { void testForImageOne() {
int image[][] = { int[][] image = {
{ 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 },
{ 0, 3, 3, 3, 3, 0, 0 }, { 0, 3, 3, 3, 3, 0, 0 },
{ 0, 3, 1, 1, 5, 0, 0 }, { 0, 3, 1, 1, 5, 0, 0 },
@ -36,7 +36,7 @@ class FloodFillTest {
{ 0, 0, 0, 3, 3, 3, 3 }, { 0, 0, 0, 3, 3, 3, 3 },
}; };
int expected[][] = { int[][] expected = {
{ 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 },
{ 0, 3, 3, 3, 3, 0, 0 }, { 0, 3, 3, 3, 3, 0, 0 },
{ 0, 3, 2, 2, 5, 0, 0 }, { 0, 3, 2, 2, 5, 0, 0 },
@ -52,7 +52,7 @@ class FloodFillTest {
@Test @Test
void testForImageTwo() { void testForImageTwo() {
int image[][] = { int[][] image = {
{ 0, 0, 1, 1, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0 },
{ 1, 1, 3, 3, 3, 0, 0 }, { 1, 1, 3, 3, 3, 0, 0 },
{ 1, 3, 1, 1, 5, 0, 0 }, { 1, 3, 1, 1, 5, 0, 0 },
@ -62,7 +62,7 @@ class FloodFillTest {
{ 0, 0, 0, 1, 3, 1, 3 }, { 0, 0, 0, 1, 3, 1, 3 },
}; };
int expected[][] = { int[][] expected = {
{ 0, 0, 2, 2, 0, 0, 0 }, { 0, 0, 2, 2, 0, 0, 0 },
{ 2, 2, 3, 3, 3, 0, 0 }, { 2, 2, 3, 3, 3, 0, 0 },
{ 2, 3, 2, 2, 5, 0, 0 }, { 2, 3, 2, 2, 5, 0, 0 },
@ -78,13 +78,13 @@ class FloodFillTest {
@Test @Test
void testForImageThree() { void testForImageThree() {
int image[][] = { int[][] image = {
{ 1, 1, 2, 3, 1, 1, 1 }, { 1, 1, 2, 3, 1, 1, 1 },
{ 1, 0, 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 0, 0, 1 },
{ 1, 1, 1, 0, 3, 1, 2 }, { 1, 1, 1, 0, 3, 1, 2 },
}; };
int expected[][] = { int[][] expected = {
{ 4, 4, 2, 3, 4, 4, 4 }, { 4, 4, 2, 3, 4, 4, 4 },
{ 4, 0, 0, 4, 0, 0, 4 }, { 4, 0, 0, 4, 0, 0, 4 },
{ 4, 4, 4, 0, 3, 4, 2 }, { 4, 4, 4, 0, 3, 4, 2 },

View File

@ -45,7 +45,7 @@ public class MazeRecursionTest {
MazeRecursion.setWay(map, 1, 1); MazeRecursion.setWay(map, 1, 1);
MazeRecursion.setWay2(map2, 1, 1); MazeRecursion.setWay2(map2, 1, 1);
int expectedMap[][] = new int[][] { int[][] expectedMap = new int[][] {
{ 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1 },
{ 1, 2, 0, 0, 0, 0, 1 }, { 1, 2, 0, 0, 0, 0, 1 },
{ 1, 2, 2, 2, 0, 0, 1 }, { 1, 2, 2, 2, 0, 0, 1 },
@ -56,7 +56,7 @@ public class MazeRecursionTest {
{ 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1 },
}; };
int expectedMap2[][] = new int[][] { int[][] expectedMap2 = new int[][] {
{ 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 1 },
{ 1, 2, 2, 2, 2, 2, 1 }, { 1, 2, 2, 2, 2, 2, 1 },
{ 1, 0, 0, 0, 0, 2, 1 }, { 1, 0, 0, 0, 0, 2, 1 },

View File

@ -7,8 +7,8 @@ public class AutomorphicNumberTest {
@Test @Test
void testAutomorphicNumber() { void testAutomorphicNumber() {
int trueTestCases[] = { 0, 1, 25, 625, 12890625}; int[] trueTestCases = { 0, 1, 25, 625, 12890625};
int falseTestCases[] = { -5, 2, 26, 1234 }; int[] falseTestCases = { -5, 2, 26, 1234 };
for (Integer n : trueTestCases) { for (Integer n : trueTestCases) {
assertTrue(AutomorphicNumber.isAutomorphic(n)); assertTrue(AutomorphicNumber.isAutomorphic(n));
assertTrue(AutomorphicNumber.isAutomorphic2(n)); assertTrue(AutomorphicNumber.isAutomorphic2(n));

View File

@ -7,8 +7,8 @@ class PerfectNumberTest {
@Test @Test
public void perfectNumber() { public void perfectNumber() {
int trueTestCases[] = { 6, 28, 496, 8128, 33550336 }; int[] trueTestCases = { 6, 28, 496, 8128, 33550336 };
int falseTestCases[] = { -6, 0, 1, 9, 123 }; int[] falseTestCases = { -6, 0, 1, 9, 123 };
for (Integer n : trueTestCases) { for (Integer n : trueTestCases) {
assertTrue(PerfectNumber.isPerfectNumber(n)); assertTrue(PerfectNumber.isPerfectNumber(n));
assertTrue(PerfectNumber.isPerfectNumber2(n)); assertTrue(PerfectNumber.isPerfectNumber2(n));

View File

@ -9,49 +9,49 @@ public class CalculateMaxOfMinTest {
@Test @Test
void testForOneElement() { void testForOneElement() {
int a[] = { 10, 20, 30, 50, 10, 70, 30 }; int[] a = { 10, 20, 30, 50, 10, 70, 30 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 70); assertTrue(k == 70);
} }
@Test @Test
void testForTwoElements() { void testForTwoElements() {
int a[] = { 5, 3, 2, 6, 3, 2, 6 }; int[] a = { 5, 3, 2, 6, 3, 2, 6 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 6); assertTrue(k == 6);
} }
@Test @Test
void testForThreeElements() { void testForThreeElements() {
int a[] = { 10, 10, 10, 10, 10, 10, 10 }; int[] a = { 10, 10, 10, 10, 10, 10, 10 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 10); assertTrue(k == 10);
} }
@Test @Test
void testForFourElements() { void testForFourElements() {
int a[] = { 70, 60, 50, 40, 30, 20 }; int[] a = { 70, 60, 50, 40, 30, 20 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 70); assertTrue(k == 70);
} }
@Test @Test
void testForFiveElements() { void testForFiveElements() {
int a[] = { 50 }; int[] a = { 50 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 50); assertTrue(k == 50);
} }
@Test @Test
void testForSixElements() { void testForSixElements() {
int a[] = { 1, 4, 7, 9, 2, 4, 6 }; int[] a = { 1, 4, 7, 9, 2, 4, 6 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 9); assertTrue(k == 9);
} }
@Test @Test
void testForSevenElements() { void testForSevenElements() {
int a[] = { -1, -5, -7, -9, -12, -14 }; int[] a = { -1, -5, -7, -9, -12, -14 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a); int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == -1); assertTrue(k == -1);
} }

View File

@ -9,49 +9,49 @@ public class CountFriendsPairingTest {
@Test @Test
void testForOneElement() { void testForOneElement() {
int a[] = { 1, 2, 2 }; int[] a = { 1, 2, 2 };
assertTrue(CountFriendsPairing.countFriendsPairing(3, a)); assertTrue(CountFriendsPairing.countFriendsPairing(3, a));
} }
@Test @Test
void testForTwoElements() { void testForTwoElements() {
int a[] = { 1, 2, 2, 3 }; int[] a = { 1, 2, 2, 3 };
assertTrue(CountFriendsPairing.countFriendsPairing(4, a)); assertTrue(CountFriendsPairing.countFriendsPairing(4, a));
} }
@Test @Test
void testForThreeElements() { void testForThreeElements() {
int a[] = { 1, 2, 2, 3, 3 }; int[] a = { 1, 2, 2, 3, 3 };
assertTrue(CountFriendsPairing.countFriendsPairing(5, a)); assertTrue(CountFriendsPairing.countFriendsPairing(5, a));
} }
@Test @Test
void testForFourElements() { void testForFourElements() {
int a[] = { 1, 2, 2, 3, 3, 4 }; int[] a = { 1, 2, 2, 3, 3, 4 };
assertTrue(CountFriendsPairing.countFriendsPairing(6, a)); assertTrue(CountFriendsPairing.countFriendsPairing(6, a));
} }
@Test @Test
void testForFiveElements() { void testForFiveElements() {
int a[] = { 1, 2, 2, 3, 3, 4, 4 }; int[] a = { 1, 2, 2, 3, 3, 4, 4 };
assertTrue(CountFriendsPairing.countFriendsPairing(7, a)); assertTrue(CountFriendsPairing.countFriendsPairing(7, a));
} }
@Test @Test
void testForSixElements() { void testForSixElements() {
int a[] = { 1, 2, 2, 3, 3, 4, 4, 4 }; int[] a = { 1, 2, 2, 3, 3, 4, 4, 4 };
assertTrue(CountFriendsPairing.countFriendsPairing(8, a)); assertTrue(CountFriendsPairing.countFriendsPairing(8, a));
} }
@Test @Test
void testForSevenElements() { void testForSevenElements() {
int a[] = { 1, 2, 2, 3, 3, 4, 4, 4, 5 }; int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5 };
assertTrue(CountFriendsPairing.countFriendsPairing(9, a)); assertTrue(CountFriendsPairing.countFriendsPairing(9, a));
} }
@Test @Test
void testForEightElements() { void testForEightElements() {
int a[] = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 }; int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 };
assertTrue(CountFriendsPairing.countFriendsPairing(10, a)); assertTrue(CountFriendsPairing.countFriendsPairing(10, a));
} }
} }

View File

@ -9,49 +9,49 @@ public class KadaneAlogrithmTest {
@Test @Test
void testForOneElement() { void testForOneElement() {
int a[] = { -1 }; int[] a = { -1 };
assertTrue(KadaneAlgorithm.max_Sum(a, -1)); assertTrue(KadaneAlgorithm.max_Sum(a, -1));
} }
@Test @Test
void testForTwoElements() { void testForTwoElements() {
int a[] = { -2, 1 }; int[] a = { -2, 1 };
assertTrue(KadaneAlgorithm.max_Sum(a, 1)); assertTrue(KadaneAlgorithm.max_Sum(a, 1));
} }
@Test @Test
void testForThreeElements() { void testForThreeElements() {
int a[] = { 5, 3, 12 }; int[] a = { 5, 3, 12 };
assertTrue(KadaneAlgorithm.max_Sum(a, 20)); assertTrue(KadaneAlgorithm.max_Sum(a, 20));
} }
@Test @Test
void testForFourElements() { void testForFourElements() {
int a[] = { -1, -3, -7, -4 }; int[] a = { -1, -3, -7, -4 };
assertTrue(KadaneAlgorithm.max_Sum(a, -1)); assertTrue(KadaneAlgorithm.max_Sum(a, -1));
} }
@Test @Test
void testForFiveElements() { void testForFiveElements() {
int a[] = { 4, 5, 3, 0, 2 }; int[] a = { 4, 5, 3, 0, 2 };
assertTrue(KadaneAlgorithm.max_Sum(a, 14)); assertTrue(KadaneAlgorithm.max_Sum(a, 14));
} }
@Test @Test
void testForSixElements() { void testForSixElements() {
int a[] = { -43, -45, 47, 12, 87, -13 }; int[] a = { -43, -45, 47, 12, 87, -13 };
assertTrue(KadaneAlgorithm.max_Sum(a, 146)); assertTrue(KadaneAlgorithm.max_Sum(a, 146));
} }
@Test @Test
void testForSevenElements() { void testForSevenElements() {
int a[] = { 9, 8, 2, 23, 13, 6, 7 }; int[] a = { 9, 8, 2, 23, 13, 6, 7 };
assertTrue(KadaneAlgorithm.max_Sum(a, 68)); assertTrue(KadaneAlgorithm.max_Sum(a, 68));
} }
@Test @Test
void testForEightElements() { void testForEightElements() {
int a[] = { 9, -5, -5, -2, 4, 5, 0, 1 }; int[] a = { 9, -5, -5, -2, 4, 5, 0, 1 };
assertTrue(KadaneAlgorithm.max_Sum(a, 10)); assertTrue(KadaneAlgorithm.max_Sum(a, 10));
} }
} }

View File

@ -9,49 +9,49 @@ public class LinkListSortTest {
@Test @Test
void testForOneElement() { void testForOneElement() {
int a[] = { 56 }; int[] a = { 56 };
assertTrue(LinkListSort.isSorted(a, 2)); assertTrue(LinkListSort.isSorted(a, 2));
} }
@Test @Test
void testForTwoElements() { void testForTwoElements() {
int a[] = { 6, 4 }; int[] a = { 6, 4 };
assertTrue(LinkListSort.isSorted(a, 1)); assertTrue(LinkListSort.isSorted(a, 1));
} }
@Test @Test
void testForThreeElements() { void testForThreeElements() {
int a[] = { 875, 253, 12 }; int[] a = { 875, 253, 12 };
assertTrue(LinkListSort.isSorted(a, 3)); assertTrue(LinkListSort.isSorted(a, 3));
} }
@Test @Test
void testForFourElements() { void testForFourElements() {
int a[] = { 86, 32, 87, 13 }; int[] a = { 86, 32, 87, 13 };
assertTrue(LinkListSort.isSorted(a, 1)); assertTrue(LinkListSort.isSorted(a, 1));
} }
@Test @Test
void testForFiveElements() { void testForFiveElements() {
int a[] = { 6, 5, 3, 0, 9 }; int[] a = { 6, 5, 3, 0, 9 };
assertTrue(LinkListSort.isSorted(a, 1)); assertTrue(LinkListSort.isSorted(a, 1));
} }
@Test @Test
void testForSixElements() { void testForSixElements() {
int a[] = { 9, 65, 432, 32, 47, 327 }; int[] a = { 9, 65, 432, 32, 47, 327 };
assertTrue(LinkListSort.isSorted(a, 3)); assertTrue(LinkListSort.isSorted(a, 3));
} }
@Test @Test
void testForSevenElements() { void testForSevenElements() {
int a[] = { 6, 4, 2, 1, 3, 6, 7 }; int[] a = { 6, 4, 2, 1, 3, 6, 7 };
assertTrue(LinkListSort.isSorted(a, 1)); assertTrue(LinkListSort.isSorted(a, 1));
} }
@Test @Test
void testForEightElements() { void testForEightElements() {
int a[] = { 123, 234, 145, 764, 322, 367, 768, 34 }; int[] a = { 123, 234, 145, 764, 322, 367, 768, 34 };
assertTrue(LinkListSort.isSorted(a, 2)); assertTrue(LinkListSort.isSorted(a, 2));
} }
} }

View File

@ -8,7 +8,7 @@ public class sortOrderAgnosticBinarySearchTest{
@Test @Test
public void testAscending(){ public void testAscending(){
int arr[] = {1,2,3,4,5};// for ascending order. int[] arr = {1,2,3,4,5};// for ascending order.
int target = 2; int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target); int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 1; int excepted = 1;
@ -17,7 +17,7 @@ public class sortOrderAgnosticBinarySearchTest{
@Test @Test
public void testDescending(){ public void testDescending(){
int arr[] = {5,4,3,2,1};// for descending order. int[] arr = {5,4,3,2,1};// for descending order.
int target = 2; int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target); int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 3; int excepted = 3;