Java Online Compiler
Example: DisjointArraySortAndPointers in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// DisjointArraySortAndPointers import java.util.Arrays; import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if two integer arrays are disjoint by sorting and using two pointers. * @param arr1 The first array. * @param arr2 The second array. * @return true if the arrays are disjoint (no common elements), false otherwise. */ public static boolean areArraysDisjointSortAndPointers(int[] arr1, int[] arr2) { // Step 1: Sort both arrays. Arrays.sort(arr1); Arrays.sort(arr2); // Step 2: Initialize two pointers, one for each array. int i = 0; // Pointer for arr1 int j = 0; // Pointer for arr2 // Step 3: Iterate while both pointers are within their respective array bounds. while (i < arr1.length && j < arr2.length) { // Step 4: If elements at current pointers are equal, a common element is found. if (arr1[i] == arr2[j]) { return false; // Not disjoint } // Step 5: If element in arr1 is smaller, move arr1's pointer forward. else if (arr1[i] < arr2[j]) { i++; } // Step 6: If element in arr2 is smaller, move arr2's pointer forward. else { // arr1[i] > arr2[j] j++; } } // Step 7: If the loops complete without finding any common elements, the arrays are disjoint. return true; } public static void main(String[] args) { // Test Case 1: Disjoint arrays int[] arr1_case1 = {1, 3, 2}; // Unsorted initially int[] arr2_case1 = {6, 4, 5}; // Unsorted initially System.out.println("Arrays: {1, 3, 2} and {6, 4, 5}"); System.out.println("Are disjoint (Sort & Pointers)? " + areArraysDisjointSortAndPointers(arr1_case1, arr2_case1)); // Expected: true // Test Case 2: Non-disjoint arrays int[] arr1_case2 = {2, 1, 3}; // Unsorted initially int[] arr2_case2 = {5, 3, 4}; // Unsorted initially System.out.println("\nArrays: {2, 1, 3} and {5, 3, 4}"); System.out.println("Are disjoint (Sort & Pointers)? " + areArraysDisjointSortAndPointers(arr1_case2, arr2_case2)); // Expected: false // Test Case 3: Empty arrays int[] arr1_case3 = {}; int[] arr2_case3 = {1, 2, 3}; System.out.println("\nArrays: {} and {1, 2, 3}"); System.out.println("Are disjoint (Sort & Pointers)? " + areArraysDisjointSortAndPointers(arr1_case3, arr2_case3)); // Expected: true } }
Output
Clear
ADVERTISEMENTS