(O)
(Ω)
(Θ)
(o)
(ω)
(O)
to analyze algorithms because:
import java.util.Scanner;
public class ArrayTraversal
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Input size of the array
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
// Input elements
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
// Traverse and print elements
System.out.println("Traversing the array:");
for (int i = 0; i < n; i++)
{
System.out.println(arr[i]);
}
}
}
Case | Description | Complexity |
---|---|---|
Worst Case | Even in the worst case, we visit every element once, so complexity is O(n) . |
O(n) |
Average Case | On average, we visit all elements once, so complexity is Θ(n) . |
Θ(n) |
Best Case | We still need to visit every element once, so complexity is Ω(n) . |
Ω(n) |
import java.util.Scanner;
public class LinearSearch
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Input size of the array
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
// Input elements
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
// Input element to search
System.out.print("Enter element to search: ");
int key = sc.nextInt();
// Linear search
boolean found = false;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
System.out.println("Element found at index: " + i);
found = true;
break;
}
}
if (!found)
{
System.out.println("Element not found in the array.");
}
}
}
Case | Description | Complexity |
---|---|---|
Worst Case | The element is either at the last position or not present at all, requiring n comparisons. |
O(n) |
Average Case | The element is found somewhere in the middle of the array, so we make about n/2 comparisons on average. |
Θ(n) |
Best Case | The element is found at the first position, so only one comparison is needed. | Ω(1) |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.