0% found this document useful (0 votes)
176 views

Search, Insert and Delete in An Unsorted Array: Searching

In an unsorted array, search, insert, and delete operations have linear time complexity of O(n). Search is done by linear traversal, insert adds the element at the end, and delete searches for the element using linear search then shifts elements. In a sorted array, search uses binary search with O(Log n) time, insert may require shifting elements with O(n) time in worst case, and delete searches using binary search then shifts elements. To find pairs summing to a specific value, an algorithm first sorts the array then uses two indices moving inward to find a pair with the desired sum in O(nLogn) time.

Uploaded by

priyanjay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
176 views

Search, Insert and Delete in An Unsorted Array: Searching

In an unsorted array, search, insert, and delete operations have linear time complexity of O(n). Search is done by linear traversal, insert adds the element at the end, and delete searches for the element using linear search then shifts elements. In a sorted array, search uses binary search with O(Log n) time, insert may require shifting elements with O(n) time in worst case, and delete searches using binary search then shifts elements. To find pairs summing to a specific value, an algorithm first sorts the array then uses two indices moving inward to find a pair with the desired sum in O(nLogn) time.

Uploaded by

priyanjay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Searching :

Search, insert and delete in an


unsorted array
Search Operation
In an unsorted array, the search operation can be performed by linear traversal from
the first element to the last element.
// Java program to implement linear 
// search in unsorted arrays
  
class Main
{
    // Function to implement 
    // search operation 
    static int findElement(int arr[], int n, 
                           int key)
    {
        for (int i = 0; i < n; i++)
            if (arr[i] == key)
                return i;
       
        return -1;
    }
       
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = {12, 34, 10, 6, 40};
        int n = arr.length;
       
        // Using a last element as search element
        int key = 40;
        int position = findElement(arr, n, key);
       
        if (position == - 1)
            System.out.println("Element not found");
        else
            System.out.println("Element Found at Position: " 
                                + (position + 1));
    }
}
Output:
Element Found at Position: 5
Insert at the end
In an unsorted array, the insert operation is faster as compared to sorted array
because we don’t have to care about the position at which the element is to be
placed.

// Java program to implement insert 


// operation in an unsorted array.
  
class Main
{
    // Function to insert a given key in 
    // the array. This function returns n+1 
    // if insertion is successful, else n. 
    static int insertSorted(int arr[], int n, 
                            int key, 
                            int capacity)
    {
  
        // Cannot insert more elements if n 
        // is already more than or equal to 
        // capcity
        if (n >= capacity)
           return n;
       
        arr[n] = key;
       
        return (n + 1);
    }
       
    // Driver Code
    public static void main (String[] args)
    {   
        int[] arr = new int[20]; 
        arr[0] = 12;
        arr[1] = 16;
        arr[2] = 20;
        arr[3] = 40; 
        arr[4] = 50;
        arr[5] = 70;
        int capacity = 20;
        int n = 6;
        int i, key = 26;
       
        System.out.print("Before Insertion: ");
        for (i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
       
        // Inserting key
        n = insertSorted(arr, n, key, capacity);
       
        System.out.print("\n After Insertion: ");
        for (i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
    }
}
Output:
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 40 50 70 26
Delete Operation
In delete operation, the element to be deleted is searched using the linear
search and then delete operation is performed followed by shifting the elements.

// Java program to implement delete


// operation in an unsorted array
   
class Main
{
    // function to search a key to 
    // be deleted
    static int findElement(int arr[], int n, int key)
    {
        int i;
        for (i = 0; i < n; i++)
            if (arr[i] == key)
                return i;
       
        return -1;
    } 
      
    // Function to delete an element
    static int deleteElement(int arr[], int n, int key)
    {
        // Find position of element to be 
        // deleted
        int pos = findElement(arr, n, key);
       
        if (pos == -1)
        {
            System.out.println("Element not found");
            return n;
        }
       
        // Deleting element
        int i;
        for (i = pos; i< n - 1; i++)
            arr[i] = arr[i + 1];
       
        return n - 1;
    }
       
    // Driver Code
    public static void main(String args[])
    {
        int i;
        int arr[] = {10, 50, 30, 40, 20};
       
        int n = arr.length;
        int key = 30;
       
        System.out.println("Array before deletion");
        for (i=0; i<n; i++)
          System.out.print(arr[i] + " ");
       
        n = deleteElement(arr, n, key);
       
        System.out.println("\n\nArray after deletion");
        for (i=0; i<n; i++)
          System.out.print(arr[i]+" ");
    } 
}

Output:
Array before deletion
10 50 30 40 20

Array after deletion


10 50 40 20
Time complexities:
Search: O(n)
Insert: O(1)
Delete: O(n)

Search, insert and delete in a sorted


array
Search Operation
In a sorted array, the search operation can be performed by using binary search.

// Java program to implement binary


// search in a sorted array
  
class Main {
    // function to implement
    // binary search
    static int binarySearch(int arr[], int low, int high, int key)
    {
        if (high < low)
            return -1;
  
        /*low + (high - low)/2;*/
        int mid = (low + high) / 2;
        if (key == arr[mid])
            return mid;
        if (key > arr[mid])
            return binarySearch(arr, (mid + 1), high, key);
        return binarySearch(arr, low, (mid - 1), key);
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 5, 6, 7, 8, 9, 10 };
        int n, key;
        n = arr.length;
        key = 10;
  
        System.out.println("Index: " + binarySearch(arr, 0, n, key));
    }
}

Output:
Index: 5
Insert Operation
In an unsorted array, the insert operation is faster as compared to sorted array
because we don’t have to care about the position at which the element to be placed.

// Java program to insert an


// element in a sorted array
  
class Main {
    // Inserts a key in arr[] of given
    // capacity.  n is current size of arr[].
    // This function returns n+1 if insertion
    // is successful, else n.
    static int insertSorted(int arr[], int n, int key, int capacity)
    {
        // Cannot insert more elements if n is already
        // more than or equal to capcity
        if (n >= capacity)
            return n;
  
        int i;
        for (i = n - 1; (i >= 0 && arr[i] > key); i--)
            arr[i + 1] = arr[i];
  
        arr[i + 1] = key;
  
        return (n + 1);
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = new int[20];
        arr[0] = 12;
        arr[1] = 16;
        arr[2] = 20;
        arr[3] = 40;
        arr[4] = 50;
        arr[5] = 70;
        int capacity = arr.length;
        int n = 6;
        int key = 26;
  
        System.out.print("\nBefore Insertion: ");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
  
        // Inserting key
        n = insertSorted(arr, n, key, capacity);
  
        System.out.print("\nAfter Insertion: ");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
Output:
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 26 40 50 70
Delete Operation
In delete operation, the element to be deleted is searched using binary search and
then delete operation is performed followed by shifting the elements.
// Java program to delete an
// element from a sorted array
  
class Main {
    // binary search
    static int binarySearch(int arr[], int low, int high, int key)
    {
        if (high < low)
            return -1;
        int mid = (low + high) / 2;
        if (key == arr[mid])
            return mid;
        if (key > arr[mid])
            return binarySearch(arr, (mid + 1), high, key);
        return binarySearch(arr, low, (mid - 1), key);
    }
  
    /* Function to delete an element */
    static int deleteElement(int arr[], int n, int key)
    {
        // Find position of element to be deleted
        int pos = binarySearch(arr, 0, n - 1, key);
  
        if (pos == -1) {
            System.out.println("Element not found");
            return n;
        }
  
        // Deleting element
        int i;
        for (i = pos; i < n - 1; i++)
            arr[i] = arr[i + 1];
  
        return n - 1;
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
  
        int i;
        int arr[] = { 10, 20, 30, 40, 50 };
  
        int n = arr.length;
        int key = 30;
  
        System.out.print("Array before deletion:\n");
        for (i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
  
        n = deleteElement(arr, n, key);
  
        System.out.print("\n\nArray after deletion:\n");
        for (i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
Output:
Array before deletion
10 20 30 40 50

Array after deletion


10 20 40 50
Search: O(Log n) [Using Binary Search]
Insert: O(n) [In worst case all elements may have to be moved]
Delete: O(n) [In worst case all elements may have to be moved]

Given an array A[] and a number x,


check for pair in A[] with sum as x
METHOD 1 (Use Sorting)
Algorithm :

hasArrayTwoCandidates (A[], ar_size, sum)


1) Sort the array in non-decreasing order.
2) Initialize two index variables to find the candidate
elements in the sorted array.
(a) Initialize first to the leftmost index: l = 0
(b) Initialize second the rightmost index: r = ar_size-1
3) Loop while l < r.
(a) If (A[l] + A[r] == sum) then return 1
(b) Else if( A[l] + A[r] < sum ) then l++
(c) Else r--
4) No candidates in whole array - return 0
Time Complexity: Depends on what sorting algorithm we use. If we use Merge Sort
or Heap Sort then (-)(nlogn) in worst case. If we use Quick Sort then O(n^2) in worst
case.
Auxiliary Space : Again, depends on sorting algorithm. For example auxiliary space is
O(n) for merge sort and O(1) for Heap Sort.

Example :
Let Array be {1, 4, 45, 6, 10, -8} and sum to find be 16
Sort the array
A = {-8, 1, 4, 6, 10, 45}
We will increment’l’ when sum of pair is less than required sum and decrement ‘r’
when sum of pair is more than required sum.
This is because when sum is less than required then we need to get the number
which could increase our sum of pair so we move from left to right(also array is
sorted)thus “l++” and vice versa.
Initialize l = 0, r = 5
A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 4
A[l] + A[r] ( -8 + 10) increment l. Now l = 1
A[l] + A[r] ( 1 + 10) increment l. Now l = 2
A[l] + A[r] ( 4 + 10) increment l. Now l = 3
A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)
Note: If there are more than one pair having the given sum then this algorithm
reports only one. Can be easily extended for this though.
Below is the implementation of the above approach.
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;
  
class GFG {
    // Function to check if array has 2 elements
    // whose sum is equal to the given value
    static boolean hasArrayTwoCandidates(int A[],
                                         int arr_size, int sum)
    {
        int l, r;
  
        /* Sort the elements */
        Arrays.sort(A);
  
        /* Now look for the two candidates 
        in the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return true;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return false;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = A.length;
  
        // Function calling
        if (hasArrayTwoCandidates(A, arr_size, n))
            System.out.println("Array has two "
                               + "elements with given sum");
        else
            System.out.println("Array doesn't have "
                               + "two elements with given sum");
    }
}
Output :
Array has two elements with the given sum

METHOD 2 (Use Hashing)


This method works in O(n) time.
1) Initialize an empty hash table s.
2) Do following for each element A[i] in A[]
(a) If s[x - A[i]] is set then print the pair (A[i], x - A[i])
(b) Insert A[i] into s.
// Java implementation using Hashing
import java.io.*;
import java.util.HashSet;
  
class PairSum {
    static void printpairs(int arr[], int sum)
    {
        HashSet<Integer> s = new HashSet<Integer>();
        for (int i = 0; i < arr.length; ++i) {
            int temp = sum - arr[i];
  
            // checking for condition
            if (s.contains(temp)) {
                System.out.println("Pair with given sum " + sum + " is (" +
arr[i] + ", " + temp + ")");
            }
            s.add(arr[i]);
        }
    }
  
    // Main to test the above function
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        printpairs(A, n);
    }
}
Output:

Pair with given sum 16 is (10, 6)


Time Complexity: O(n)
Auxiliary Space: O(n) where n is size of array.
If range of numbers include negative numbers then also it works.

Find the element that appears once in


an array where every other element
appears twice
Given an array of integers. All numbers occur twice except one number which occurs
once. Find the number in O(n) time & constant extra space.
Example :
Input: ar[] = {7, 3, 5, 4, 5, 3, 4}
Output: 7
One solution is to check every element if it appears once or not. Once an element
with single occurrence is found, return it. Time complexity of this solution is O(n 2).

A better solution is to use hashing.


1) Traverse all elements and put them in a hash table. Element is used as key and
count of occurrences is used as value in hash table.
2) Traverse the array again and print the element with count 1 in hash table.
This solution works in O(n) time, but requires extra space.
The best solution is to use XOR. XOR of all array elements gives us the number with
single occurrence. The idea is based on following two facts.
a) XOR of a number with itself is 0.
b) XOR of a number with 0 is number itself.
Let us consider the above example.
Let ^ be xor operator as in C and C++.

res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above


expression can be written as:
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
=7^0^0^0
=7^0
=7
// Java program to find the array 
// element that appears only once
class MaxSum
{
    // Return the maximum Sum of difference
    // between consecutive elements.
    static int findSingle(int ar[], int ar_size)
    {
        // Do XOR of all elements and return
        int res = ar[0];
        for (int i = 1; i < ar_size; i++)
            res = res ^ ar[i];
      
        return res;
    }
  
    // Driver code
    public static void main (String[] args)
    {
        int ar[] = {2, 3, 5, 4, 5, 3, 4};
        int n = ar.length;
        System.out.println("Element occurring once is " +
                            findSingle(ar, n) + " ");
    }
}
Output:
Element occurring once is 2
Time complexity of this solution is O(n) and it requires O(1) extra space.
Another approach:
This is not an efficient approach but just another way to get the desired results. If we
add each number once and multiply the sum by 2, we will get twice sum of each
element of the array. Then we will subtract the sum of the whole array from the
twice_sum and get the required number (which appears once in the array).
Array [] : [a, a, b, b, c, c, d]
Mathematical Equation = 2*(a+b+c+d) – (a + a + b + b + c + c + d)
In more simple words: 2*(sum_of_array_without_duplicates) – (sum_of_array)
let arr[] = {7, 3, 5, 4, 5, 3, 4}
Required no = 2*(sum_of_array_without_duplicates) - (sum_of_array)
= 2*(7 + 3 + 5 + 4) - (7 + 3 + 5 + 4 + 5 + 3 + 4)
= 2* 19 - 31
= 38 - 31
= 7 (required answer)
As we know that set does not contain any duplicate element we will be using
the set here.
// Java program to find 
// element that appears once
import java.io.*;
import java.util.*;
  
class GFG 
{
  
    // function which find number
    static int singleNumber(int[] nums, int n)
    {
        HashMap<Integer, Integer> m = new HashMap<>();
        long sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++)
        {
            if (!m.containsKey(nums[i]))
            {
                sum1 += nums[i];
                m.put(nums[i], 1);
            }
            sum2 += nums[i];
        }
  
        // applying the formula.
        return (int)(2 * (sum1) - sum2); 
    }
  
    // Driver code
    public static void main(String args[])
    {
        int[] a = {2, 3, 5, 4, 5, 3, 4};
        int n = 7;
        System.out.println(singleNumber(a,n));
  
        int[] b = {15, 18, 16, 18, 16, 15, 89};
        System.out.println(singleNumber(b,n));
    }

Output:
2
89

Leaders in an array
Write a program to print all the LEADERS in the array. An element is leader if it is
greater than all the elements to its right side. And the rightmost element is always a
leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Let the input array be arr[] and size of the array be size.
Method 1 (Simple)
Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all
elements from left to right. The inner loop compares the picked element to all the
elements to its right side. If the picked element is greater than all the elements to its
right side, then the picked element is the leader.

class LeadersInArray 
{
    /*Java Function to print leaders in an array */
    void printLeaders(int arr[], int size) 
    {
        for (int i = 0; i < size; i++) 
        {
            int j;
            for (j = i + 1; j < size; j++) 
            {
                if (arr[i] <= arr[j])
                    break;
            }
            if (j == size) // the loop didn't break
                System.out.print(arr[i] + " ");
        }
    }
  
    /* Driver program to test above functions */
    public static void main(String[] args) 
    {
        LeadersInArray lead = new LeadersInArray();
        int arr[] = new int[]{16, 17, 4, 3, 5, 2};
        int n = arr.length;
        lead.printLeaders(arr, n);
    }
}
Output:
17 5 2
Time Complexity: O(n*n)

Method 2 (Scan from right)


Scan all the elements from right to left in an array and keep track of maximum till
now. When maximum changes its value, print it.
Below image is a dry run of the above approach:

class LeadersInArray 
{
    /* Java Function to print leaders in an array */
    void printLeaders(int arr[], int size)
    {
        int max_from_right =  arr[size-1];
   
        /* Rightmost element is always leader */
        System.out.print(max_from_right + " ");
       
        for (int i = size-2; i >= 0; i--)
        {
            if (max_from_right < arr[i])
            {           
            max_from_right = arr[i];
            System.out.print(max_from_right + " ");
            }
        }    
    }
  
    /* Driver program to test above functions */
    public static void main(String[] args) 
    {
        LeadersInArray lead = new LeadersInArray();
        int arr[] = new int[]{16, 17, 4, 3, 5, 2};
        int n = arr.length;
        lead.printLeaders(arr, n);
    }
}
Output:
2 5 17

Time Complexity: O(n)

Majority Element
Write a function which takes an array and prints the majority element (if it exists),
otherwise prints “No Majority Element”. A majority element in an array A[] of size n
is an element that appears more than n/2 times (and hence there is at most one
such element).
Examples :
Input : {3, 3, 4, 2, 4, 4, 2, 4, 4}
Output : 4

Input : {3, 3, 4, 2, 4, 4, 2, 4}
Output : No Majority Element

METHOD 1 (Basic)
The basic solution is to have two loops and keep track of maximum count for all
different elements. If maximum count becomes greater than n/2 then break the
loops and return the element having maximum count. If maximum count doesn’t
become more than n/2 then majority element doesn’t exist.
Below is the implementation of the above approach :
// Java  program to find Majority 
// element in an array 
  
import java.io.*;
  
class GFG {
      
// Function to find Majority element 
// in an array 
static void findMajority(int arr[], int n) 

    int maxCount = 0; 
    int index = -1; // sentinels 
    for(int i = 0; i < n; i++) 
    { 
        int count = 0; 
        for(int j = 0; j < n; j++) 
        { 
            if(arr[i] == arr[j]) 
            count++; 
        } 
          
        // update maxCount if count of 
        // current element is greater 
        if(count > maxCount) 
        { 
            maxCount = count; 
            index = i; 
        } 
    } 
      
    // if maxCount is greater than n/2 
    // return the corresponding element 
    if (maxCount > n/2) 
    System.out.println (arr[index]); 
      
    else
    System.out.println ("No Majority Element"); 

  
// Driver code 
    public static void main (String[] args) {
  
        int arr[] = {1, 1, 2, 1, 3, 5, 1}; 
        int n = arr.length; 
      
    // Function calling 
    findMajority(arr, n); 
    }
//This code is contributed by ajit.    
}
Output :
1
Time Complexity : O(n*n).
Auxiliary Space : O(1).
(Using Hashmap) :This method is somewhat similar to Moore voting algorithm in
terms of time complexity, but in this case there is no need of second step of Moore
voting algorithm.But as usual, here space complexity becomes O(n).
In Hashmap(key-value pair), at value,maintain a count for each element(key) and
whenever count is greater than half of array length, we are just returning that
key(majority element).
Time Complexity : O(n)
Auxiliary Space : O(n)
import java.util.HashMap;
  
/* Program for finding out majority element in an array */
   
class MajorityElement 
{
    private static void findMajority(int[] arr) 
    {
        HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
  
        for(int i = 0; i < arr.length; i++) {
            if (map.containsKey(arr[i])) {
                    int count = map.get(arr[i]) +1;
                    if (count > arr.length /2) {
                        System.out.println("Majority found :- " + arr[i]);
                        return;
                    } else
                        map.put(arr[i], count);
  
            }
            else
                map.put(arr[i],1);
            }
            System.out.println(" No Majority element");
    }
  
   
    /* Driver program to test the above functions */
    public static void main(String[] args) 
    {
        int a[] = new int[]{2,2,2,2,5,5,2,3,3};
          
        findMajority(a);
    }
}
Output:
Majority found :- 2

You might also like