Search, Insert and Delete in An Unsorted Array: Searching
Search, Insert and Delete in An Unsorted Array: Searching
Output:
Array before deletion
10 50 30 40 20
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.
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
res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
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)
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