Array Algorithms and Implementations
Array Algorithms and Implementations
1
DATA STRUCTURE GROUP PRESENTATION
Print the elements of the created array using the printArray method.
public static void main(String[] args) {
int[] numbers = createIntArray(5);
System.out.println("Array Elements:");
printArray(numbers);
}
System.out.println("\nArray 2 Elements:");
printArray(numbers2);
System.out.println("\nArray 3 Elements:");
2
DATA STRUCTURE GROUP PRESENTATION
printArray(numbers3);
}
3
DATA STRUCTURE GROUP PRESENTATION
4
DATA STRUCTURE GROUP PRESENTATION
// Declare an array
int[] myArray = {1, 2, 3, 4, 5};
• Copy all elements from the original array array to the new array newArray up to the
index n - 1.
4)Insert the new element:
• Insert the new element element at the last index of the new array newArray (at index
n).
5)Output:
• The new array newArray is the modified array with the inserted element at the end.
5
DATA STRUCTURE GROUP PRESENTATION
// Example array
int[] array = {1, 2, 3, 4, 5};
// Element to insert
int elementToInsert = 6;
return newArray;
6
DATA STRUCTURE GROUP PRESENTATION
}
}
• Iterate through the array to find the index of the element to delete
(elementToDelete).
3)Shift elements to fill the gap:
• If the element is found, shift all elements to the left, starting from the index after the
element to delete, effectively overwriting the element to be deleted.
4)Create a new array:
• Create a new array newArray with a size one less than the original array.
5)Copy elements to the new array:
• Copy elements from the modified array (after shifting) to the new array.
6)Output:
• The array newArray is the modified array with the specified element deleted.
// Element to delete
int elementToDelete = 3;
7
DATA STRUCTURE GROUP PRESENTATION
8
DATA STRUCTURE GROUP PRESENTATION
return newArray;
} else {
// If the element is not found, return the original array
return array;
}
}
}
Algorithm to merge arrays
1)Input:
• Calculate the length of the merged array by adding the lengths of array1 and array2.
3)Create a new array:
• Create a new array mergedArray with a length equal to the sum of the lengths of
array1 and array2.
4)Copy elements from array1 to mergedArray:
9
DATA STRUCTURE GROUP PRESENTATION
// Example arrays
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
// Merge arrays
int[] mergedArray = mergeArrays(array1, array2);
return mergedArray;
}
10
DATA STRUCTURE GROUP PRESENTATION
• Declare an array of integers named array and assign values to it: {1, 2, 3, 4, 5}.
int[] array = {1, 2, 3, 4, 5};
2)Traverse the Array:
• Display a header indicating that the following output represents the elements of the
array.
System.out.println("Array Elements:");
4)Print Each Element:
• Inside the loop, print each element along with its corresponding index.
System.out.println("Element at index " + i + ": " + array[i]);
The algorithm traverses the array from the first element to the last, printing each element
along with its index.
11
DATA STRUCTURE GROUP PRESENTATION
Function bubbleSort(array):
size = length(array)
12
DATA STRUCTURE GROUP PRESENTATION
Function main():
// initialize array
data = [-2, 45, 0, 11, -9]
import java.util.Arrays;
class Bubble{
13
DATA STRUCTURE GROUP PRESENTATION
swapped = true;
}
}
// no swapping means the array is already sorted
// so no need for further comparison
if (!swapped)
break;
14
DATA STRUCTURE GROUP PRESENTATION
}
}
15
DATA STRUCTURE GROUP PRESENTATION
16
DATA STRUCTURE GROUP PRESENTATION
Class Main:
Function main():
// initialize array
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(arrayToString(data))
size = length(data)
class QuickSort {
17
DATA STRUCTURE GROUP PRESENTATION
18
DATA STRUCTURE GROUP PRESENTATION
// Main class
class Main {
public static void main(String args[]) {
int[] data = { 8, 7, 2, 1, 0, 9, 6 };
System.out.println("Unsorted Array");
System.out.println(Arrays.toString(data));
19
DATA STRUCTURE GROUP PRESENTATION
}
}
Algorithm printArray(arr):
Input: An array arr
Algorithm main():
1. Create a SelectionSort object ob.
2. Create an array arr with elements {64, 25, 12, 22, 11}.
3. Call ob.sort(arr) to sort the array using Selection Sort.
20
DATA STRUCTURE GROUP PRESENTATION
21
DATA STRUCTURE GROUP PRESENTATION
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
22
DATA STRUCTURE GROUP PRESENTATION
// Example usage:
arr = [12, 34, 54, 2, 3]
shellSort(arr)
Implementation of the algorithm to shell sort an array
public class ShellSort {
public static void main(String[] args) {
int[] array = {12, 34, 54, 2, 3};
System.out.println("Original Array:");
printArray(array);
shellSort(array);
System.out.println("\nSorted Array:");
printArray(array);
}
23
DATA STRUCTURE GROUP PRESENTATION
24
DATA STRUCTURE GROUP PRESENTATION
// Example usage:
array = [4, 2, 7, 1, 9, 5, 6, 8, 3]
target = 5
result = sequentialSearch(array, target)
if result != -1:
print("Element", target, "found at index", result)
else:
print("Element", target, "not found in the array")
Implementation of the sequential search algorithm of an array
public class SequentialSearch {
public static void main(String[] args) {
int[] array = {4, 2, 7, 1, 9, 5, 6, 8, 3};
int target = 5;
if (result != -1) {
System.out.println("Element " + target + " found at index " + result);
} else {
System.out.println("Element " + target + " not found in the array");
}
}
25
DATA STRUCTURE GROUP PRESENTATION
26
DATA STRUCTURE GROUP PRESENTATION
if array[mid] == target:
return mid // Element found, return its index
else if array[mid] < target:
low = mid + 1 // Discard the left half
else:
high = mid - 1 // Discard the right half
// Example usage:
sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binarySearch(sortedArray, target)
if result != -1:
print("Element", target, "found at index", result)
else:
print("Element", target, "not found in the array")
Implementation of the Binary search algorithm of an array
public class BinarySearch {
public static void main(String[] args) {
int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
if (result != -1) {
System.out.println("Element " + target + " found at index " + result);
} else {
27
DATA STRUCTURE GROUP PRESENTATION
if (array[mid] == target) {
return mid; // Element found, return its index
} else if (array[mid] < target) {
low = mid + 1; // Discard the left half
} else {
high = mid - 1; // Discard the right half
}
}
28
DATA STRUCTURE GROUP PRESENTATION
2)Initialize: Set low to 0 (the beginning of the array) and high to array.length - 1 (the end of
the array).
3)While loop: While low is less than or equal to high and the target is within the range of
elements from array[low] to array[high]:
a. Calculate the estimated position pos using the interpolation formula: pos = low + ((target
- array[low]) * (high - low)) / (array[high] - array[low])
b. If array[pos] is equal to the target: - Return pos as the index of the target element.
c. If array[pos] is less than the target: - Adjust the search range to the right: set low to pos +
1.
d. If array[pos] is greater than the target: - Adjust the search range to the left: set high to
pos - 1.
4)Return -1: If the loop completes without finding a match, return -1 to indicate that the
target element is not present in the array.
if (result != -1) {
System.out.println("Element " + target + " found at index " + result);
} else {
System.out.println("Element " + target + " not found in the array");
}
}
29
DATA STRUCTURE GROUP PRESENTATION
int low = 0;
int high = array.length - 1;
while (low <= high && target >= array[low] && target <= array[high]) {
int pos = low + ((target - array[low]) * (high - low)) / (array[high] - array[low]);
if (array[pos] == target) {
return pos; // Element found, return its index
} else if (array[pos] < target) {
low = pos + 1; // Adjust the search range to the right
} else {
high = pos - 1; // Adjust the search range to the left
}
}
30
DATA STRUCTURE GROUP PRESENTATION
If the target is less than the middle element, repeat the search in the left half (high = mid -
1).
If the target is greater than the middle element, repeat the search in the right half (low =
mid + 1).
4)Base Case:
If low is greater than high, the target is not in the array; return -1.
5)Recursion:
Recursively repeat steps 2-4 on the selected half until the base case is reached.
PSEUDOCODE
function binarySearch(array, target, low, high):
if low <= high:
mid = (low + high) / 2
if array[mid] == target:
return mid
else if array[mid] > target:
return binarySearch(array, target, low, mid - 1)
else:
return binarySearch(array, target, mid + 1, high)
else:
return -1
ITS IMPLEMENTATION
public class DivideAndConquer {
private static int binarySearch(int[] array, int target, int low, int high) {
31
DATA STRUCTURE GROUP PRESENTATION
if (result != -1) {
32
DATA STRUCTURE GROUP PRESENTATION
• This variable will be used to count the number of coins needed to make change for
the given amount.
Iterate through each coin in the sorted coins array:
int coinCount = 0;
33
DATA STRUCTURE GROUP PRESENTATION
return coinCount;
}
34
DATA STRUCTURE GROUP PRESENTATION
35
DATA STRUCTURE GROUP PRESENTATION
36
DATA STRUCTURE GROUP PRESENTATION
2)Initialize Table:
Create an array fib of size n + 1 to store intermediate results of Fibonacci numbers.
Initialize fib[0] to 0 (the 0th Fibonacci number) and fib[1] to 1 (the 1st Fibonacci number).
3)Tabulation Loop:
Use a loop to iteratively calculate Fibonacci numbers from index 2 to n.
For each index i, set fib[i] to the sum of the two preceding Fibonacci numbers, fib[i - 1] and
fib[i - 2].
4)Result:
After the loop, fib[n] contains the Fibonacci number at index n, which is the result.
5)Return Result:
Return the calculated Fibonacci number fib[n].
Implementation of the Fibonacci tabulation algorithm
public class FibonacciTabulation {
public static void main(String[] args) {
int n = 10;
System.out.println("Fibonacci(" + n + "): " + fibonacci(n));
}
return fib[n];
37
DATA STRUCTURE GROUP PRESENTATION
}
}
Backtracking algorithm to solve Hamiltonian circuit problem
function HamiltonianCircuit(graph):
vertices = number of vertices in graph
path = array of size vertices filled with -1
path[0] = 0 // Start from the first vertex
path[position] = -1 // Backtrack
return false
38
DATA STRUCTURE GROUP PRESENTATION
return true
function printSolution(path):
print("Hamiltonian Circuit:")
for i from 0 to number of vertices - 1:
print(path[i] + " ")
print(path[0]) // Print the starting vertex again to complete the circuit
Implementation of the backtracking algorithm
import java.util.Arrays;
39
DATA STRUCTURE GROUP PRESENTATION
if (hamiltonianCircuitUtil(1)) {
printSolution();
} else {
System.out.println("No Hamiltonian circuit exists");
}
}
if (hamiltonianCircuitUtil(position + 1)) {
return true;
}
40
DATA STRUCTURE GROUP PRESENTATION
return false;
}
return true;
}
41
DATA STRUCTURE GROUP PRESENTATION
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 1},
{1, 1, 0, 1, 1},
{1, 0, 1, 0, 0},
{0, 1, 1, 0, 0}
};
42
DATA STRUCTURE GROUP PRESENTATION
@Override
public int compareTo(Node other) {
return Double.compare(other.bound, this.bound);
}
}
43
DATA STRUCTURE GROUP PRESENTATION
private static double bound(int level, int weight, int profit, int[] values, int[] weights, int
capacity) {
if (weight >= capacity) {
return 0; // Cannot add more weight
}
int i = level + 1;
int totalWeight = weight;
if (i < values.length) {
bound += (capacity - totalWeight) * ((double) values[i] / weights[i]);
}
return bound;
}
44
DATA STRUCTURE GROUP PRESENTATION
priorityQueue.add(rootNode);
int maxProfit = 0;
while (!priorityQueue.isEmpty()) {
Node node = priorityQueue.poll();
return maxProfit;
}
45
DATA STRUCTURE GROUP PRESENTATION
46
DATA STRUCTURE GROUP PRESENTATION
47
DATA STRUCTURE GROUP PRESENTATION
if (head == null) {
System.out.println("List is empty.");
return;
}
if (head.name.equals(key)) {
newNode.next = head;
48
DATA STRUCTURE GROUP PRESENTATION
head = newNode;
return;
}
49
DATA STRUCTURE GROUP PRESENTATION
if (head.next.name.equals(key)) {
head = head.next;
return;
}
50
DATA STRUCTURE GROUP PRESENTATION
System.out.println("Key not found or no element to delete after the key: " + key);
}
Implementation For mergeLists
public static Student mergeLists(Student s, Student s1) {
Student mergedStudentList = new Student();
// if (s.head == null) {
// mergedStudentList.head = s1.head;
// return mergedStudentList;
// }
51
DATA STRUCTURE GROUP PRESENTATION
if (s1.head != null) {
current.next = s1.head;
}
mergedStudentList.head = s.head;
return mergedStudentList;
}
Implementation For Searching
public boolean search(String searchKey) {
StudentNode current = head;
int position = 0;
}
current = current.next;
}
System.out.println("Element not found");
return false;
} Implementation For copyingList
public Student copyList() {
52
DATA STRUCTURE GROUP PRESENTATION
return copiedList;
}
53
DATA STRUCTURE GROUP PRESENTATION
s.insertAtBeginning("Annet");
s.insertAtEnd("Ukasha");
s.insertAfterKey("Shafik", "Nashif");
s.insertBeforeKey("Shafik", "Imran");
s.deleteAtBeginning();
s.deleteAtEnd();
s.deleteBeforeKey("Shafik");
s.deleteAfterKey("Shafik");
s.search("Tasha");
s.traverseAndPrint();
System.out.println("Copied List:");
Student copiedList = s.copyList();
copiedList.traverseAndPrint();
54
DATA STRUCTURE GROUP PRESENTATION
}
}
DOUBLE LINKEDLIST
public class Student1 {
private Student1Node head;
private Student1Node tail;
private int length;
public class Student1Node {
int age;
Student1Node next;
Student1Node prev;
public Student1Node(int age){
this.age=age;
this.next=null;
this.prev=null;
}
}
public Student1(){
this.head=null;
this.tail=null;
this.length=0;
}
public boolean isEmpty(){
return length==0;
}
public void append(int age) {
55
DATA STRUCTURE GROUP PRESENTATION
56
DATA STRUCTURE GROUP PRESENTATION
} else {
n.next = head;
head.prev = n;
head = n;
}
}
public void deleteAtEnd() {
if (head == null || head == tail) {
head = tail = null;
} else {
tail = tail.prev;
tail.next = null;
}
}
public void deleteAtBeginning() {
if (head == null || head == tail) {
head = tail = null;
} else {
head = head.next;
head.prev = null;
}
}
public void merge(Student1 listToMerge) {
if (listToMerge.head != null) {
if (head == null) {
head = listToMerge.head;
tail = listToMerge.tail;
} else {
tail.next = listToMerge.head;
57
DATA STRUCTURE GROUP PRESENTATION
listToMerge.head.prev = tail;
tail = listToMerge.tail;
}
}
}
public static void main(String[] args) {
Student1 s=new Student1();
Student1 s2=new Student1();
s.append(21);
s.append(24);
s.append(23);
s.append(22);
s2.append(31);
s2.append(34);
s2.append(33);
s2.append(32);
s. insertAtBeginning(20);
// s.deleteAtEnd();
// s.deleteAtBeginning();
s.merge(s2);
s.traverse1();
s.traverse2();
}
}
Binarytree
import java.util.LinkedList;
import java.util.Queue;
58
DATA STRUCTURE GROUP PRESENTATION
this.data = data;
public BinaryTree() {
root = B;
B.right = C;
B.left = A;
59
DATA STRUCTURE GROUP PRESENTATION
if (root == null) {
} else {
InsertNode(root, value);
if (node.left == null) {
} else {
InsertNode(node.left, value);
} else {
if (node.right == null) {
} else {
InsertNode(node.right, value);
if (root == null) {
if (root.data == value) {
60
DATA STRUCTURE GROUP PRESENTATION
} else {
if (root != null) {
Postorder(root.left);
Postorder(root.right);
System.out.print(root.data );
if (root != null) {
System.out.print(root.data );
Preorder(root.left);
Preorder(root.right);
if (root != null) {
Inorder(root.left);
System.out.print(root.data );
Inorder(root.right);
61
DATA STRUCTURE GROUP PRESENTATION
Q.add(root);
while (!Q.isEmpty()) {
System.out.println(current.data);
if (current.left != null) {
Q.add(current.left);
if (current.right != null) {
Q.add(current.right);
if (root == null) {
System.out.println("Tree is empty");
return null;
62
DATA STRUCTURE GROUP PRESENTATION
if (value == current.data) {
return null;
return current;
parent = current;
current = current.left;
} else {
return current
parent = current;
current = current.right;
return null;
tree.CreateTree();
tree.Insert(7) ;
tree.Contains(tree.root,6);
tree.findParent(3, tree.root);
63
DATA STRUCTURE GROUP PRESENTATION
System.out.println("Preorder traversal:");
tree.Preorder(tree.root);
System.out.println("Postorder traversal:");
tree.Postorder(tree.root);
System.out.println("Inorder traversal:");
tree.Inorder(tree.root);
System.out.println("BreadthFirst traversal:");
tree.BreadthFirst(tree.root);
this.data = data;
public BinaryTreeOne() {
64
DATA STRUCTURE GROUP PRESENTATION
root = B;
B.right = C;
B.left = A;
if (root != null) {
if (isOperand(root.data)) {
} else {
System.out.print("( ");
infix(root.left);
infix(root.right);
System.out.print(") ");
65
DATA STRUCTURE GROUP PRESENTATION
tree.CreateTree();
System.out.println("Infix notation:");
tree.infix(tree.root);
import java.util.*;
import java.util.Queue;
public Queue_Enqueue_Single(){
this.front=null;
this.rear=null;
//If the queue is empty, set set both the front and the rear to new node
if (isEmpty()){
} else {
//otherwise, add the new node at the end (Rear) of the queue
rear.nextNode = newNode;
rear = newNode;
66
DATA STRUCTURE GROUP PRESENTATION
if(isEmpty()){
return;
currentNode = currentNode.nextNode;
System.out.println();
class EnqueueImplementation{
myQueue.enqueue(13);
myQueue.enqueue(22);
myQueue.enqueue(30);
myQueue.enqueue(113);
myQueue.enqueue(55);
myQueue.enqueue(7);
67
DATA STRUCTURE GROUP PRESENTATION
System.out.print("");
myQueue.display();
public Queue_Dequeue_Single() {
this.front = null;
this.rear = null;
// If the queue is empty, set both front and rear to the new node
if (isEmpty()) {
} else {
// Otherwise, add the new node to the end (rear) of the queue
rear.nextNode = newNode;
rear = newNode;
68
DATA STRUCTURE GROUP PRESENTATION
if (isEmpty()) {
return;
// If there is only one element in the queue, set front and rear to null
if (front == rear) {
} else {
front = front.nextNode;
if (isEmpty()) {
System.out.println("Queue is empty.");
return;
69
DATA STRUCTURE GROUP PRESENTATION
currentNode = currentNode.nextNode;
System.out.println();
class DequeueImplement {
mySingleQueue.enqueue(2024);
mySingleQueue.enqueue(2023);
mySingleQueue.enqueue(2022);
mySingleQueue.display();
// Dequeue an element
mySingleQueue.dequeue();
mySingleQueue.display();
//import java.util.*;
70
DATA STRUCTURE GROUP PRESENTATION
public Stack_Pop_Single() {
this.topNode = null;
// Step 2: Set the next pointer of the new node to point to the current top of the
Stack_Push_Single
newNode.nextNode = topNode;
topNode = newNode;
// POP operation
// Step 1: If the stack is empty, return an indication that the stack is empty
if (topNode == null) {
System.out.println("Stack is empty.");
return -1; // Assuming -1 is an indication of an empty stack for integers; adjust accordingly
// Step 2: Create a temporary variable to hold the current top of the stack
71
DATA STRUCTURE GROUP PRESENTATION
topNode = topNode.nextNode;
return temp.dataValue;
currentNode = currentNode.nextNode;
System.out.println();
class ImplementStack {
stack.push(1);
stack.push(2);
stack.push(10);
stack.push(101);
stack.push(30);
stack.push(37);
72
DATA STRUCTURE GROUP PRESENTATION
stack.display();
System.out.println("\nPOPPED ELEMENTS:");
stack.display();
//import java.util.*;
public Stack_Pop_Single() {
this.topNode = null;
// PUSH operation
73
DATA STRUCTURE GROUP PRESENTATION
// Step 2: Set the next pointer of the new node to point to the current top of the
Stack_Push_Single
newNode.nextNode = topNode;
topNode = newNode;
// Step 1: If the stack is empty, return an indication that the stack is empty
if (topNode == null) {
System.out.println("Stack is empty.");
return -1; // Assuming -1 is an indication of an empty stack for integers; adjust accordingly
// Step 2: Create a temporary variable to hold the current top of the stack
topNode = topNode.nextNode;
return temp.dataValue;
currentNode = currentNode.nextNode;
74
DATA STRUCTURE GROUP PRESENTATION
System.out.println();
class ImplementStack {
stack.push(1);
stack.push(2);
stack.push(10);
stack.push(101);
stack.push(30);
stack.push(37);
stack.display();
System.out.println("\nPOPPED ELEMENTS:");
75
DATA STRUCTURE GROUP PRESENTATION
stack.display();
76