QA Friend - Quality Assurance , Software Testing & Automation Tutorials


  • Home
  • C#-UI-Automation-Tutorial
  • QTP-UFT-Tutorial
  • Selenium
  • Algorithms-Tutorials
  • Software Testing
  • Agile
  • Software-Metrics
  • Software-Effort-Estimation
  • PMP
  • UnitTest-CppUnit-C++
  • ALM-Quality-Center
  • SQL-Database-Designing
  • Contact-Us
  • Binary-Search-Java
  • Hashmap
  • Priority-Queue-Heap
  • Big-O-Notation-Tutorial
  • Count-repeating-words-in-a-list-or-an-ArrayList
  • Fibonnaci-algorithm-java
  • Determining-a-Prime-Number-in-Java
  • Tree-Traversal-Add-Node
  • Tree-Traversal-Java-In-Order
  • Tree-Traversal-Java-Post-Order
  • Tree-traversal-In-Java-Pre-Order
  • Tree-Traversal-In-Java-Find-a-Node
  • Bubble-Sort-Java
  • Bubble-Sort
  • Quick-Sort
  • Sorted-Array-Common-Elements
  • Uncommon-Elements-two-array
  • No-Duplicate-Array-Java
  • Reverse-Characters-Array
  • Array-Common-elements-using-hash-map-single-pass
  • Find-Duplicates-in-array
  • Find-multiple-duplicates-in-an-array
  • Create-a-linkedlist-inJava
  • linkedlist-find-a-node
  • LinkedList-DeleteNode-Java
  • Linked-List-Remove-Duplicates
  • Find-Node-From-End-of-a-Linked-List
  • Reverse-Linked-List-Java
  • Linked-List-Check-Palindrome
  • Merge-two-linkedList-Java
  • Insertion-Sort-Linked-List-Java
  • Find-middle-of-linked-list-in-single-pass

Finding Common Elements of two Sorted Arrays

Logic:

While both array pointers are less than array lengths, Compare two first elements of the two arrays. If first element of first array is bigger
than first element of 2nd array , then move to 2nd element of 2nd array.

Again compare  2nd element of 2nd array to first element of 1st array. If the 2nd element of 2nd array is bigger than 1st element of first array, then move to 2nd element of 1st array.

If both are  equal, print , and move to next elements of both arrays.

 sorted-array-common-elements

public class Arry
{
  public static void main(String[] args)
    {
        int FirstArray[] = { 11, 23, 44, 65, 87, 98 };
        int SecondArray[] = { 2, 23, 44, 65, 66 , 98 };
        SortedArray ref= new SortedArray();
        ref.getCommon(FirstArray, SecondArray);
    }
}
 class SortedArray
 {
     void getCommon(int[] First, int[] Second) {
     int i = 0, j = 0;
     System.out.println("Common array elements are : ");
      while (i < First.length && j < Second.length)
      {       
            if (First[i] > Second[j])
            {
                j++;
            }
            else if (Second[j] > First[i])
            {
                i++;
            }
            else
            {
                System.out.println(First[i]);
                i++;
                j++;
            }
        }
    }
}
 



Copyright  QA Friend Software Testing. All rights reserved.