Search Operation in An Unsorted Array, The Search Operation Can Be Performed by Linear Traversal From The First Element To The Last Element
Search Operation in An Unsorted Array, The Search Operation Can Be Performed by Linear Traversal From The First Element To The Last Element
In an unsorted array, the search operation can be performed by linear traversal from the first
element to the last element.
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;
if (position == - 1)
System.out.println("Element not found");
else
System.out.println("Element Found at Position: "
+ (position + 1));
}
}
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;
// Inserting key
n = insertSorted(arr, n, key, capacity);
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.
return -1;
}
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;
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