public class MainApp1
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
// Traversal using for-each loop
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 30 40 50
public class MainApp2
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
int pos = 2; // index where we want to insert
int element = 99;
// Shifting elements to the right
for (int i = arr.length - 1; i > pos; i--)
{
arr[i] = arr[i - 1];
}
arr[pos] = element; // Insert element at position
// Traversing updated array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 99 30 40
public class MainApp3
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
int pos = 2; // index of element to delete
// Shifting elements to the left
for (int i = pos; i < arr.length - 1; i++)
{
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = 0; // Optional: set last element to 0
// Traversing updated array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 40 50 0
public class MainApp4
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
int pos = 2; // index to update
int newValue = 99;
// Updating element at given index
arr[pos] = newValue;
// Traversing updated array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 99 40 50
public class MainApp5
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40, 50};
int key = 30;
boolean found = false;
// Linear search
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == key)
{
System.out.println("Element found at index: " + i);
found = true;
break;
}
}
if (!found)
{
System.out.println("Element not found");
}
}
}
Element found at index: 2
import java.util.Arrays;
public class MainApp6a
{
public static void main(String[] args)
{
int[] arr = {40, 10, 30, 50, 20};
// Sorting array in ascending order using Arrays.sort()
Arrays.sort(arr);
// Traversing sorted array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 30 40 50
public class MainApp6b
{
public static void main(String[] args)
{
int[] arr = {40, 10, 30, 50, 20};
// Bubble Sort in ascending order
for (int i = 0; i < arr.length - 1; i++)
{
for (int j = 0; j < arr.length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Traversing sorted array
for (int no : arr)
{
System.out.print(no + " ");
}
}
}
10 20 30 40 50
Arrays.sort()
is pre-defined way to sort an array, but there are many custom algorithms which are as follows:
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.