A Beginner's Guide to Arrays in Data Structures
Arrays are one of the fundamental data structures, serving as the building blocks for many algorithms and applications. Let's dive into the world of arrays and understand their significance, operations, and applications! 🚀
What is an Array exactly ?
An array is a collection of elements stored in contiguous memory locations, each identified by an index or a key. These elements are typically of the same data type, allowing for easy access and manipulation📦.
Key Features of Arrays:
Fixed Size: Imagine you have a chocolate box with 6 slots, each slot holding a chocolate bar. Once you decide to use this box 📦, you cannot add or remove slots. It stays fixed at 6. This is like an array with a fixed size. It's perfect when you know exactly how many chocolates🍫 you want to store and you don't plan on changing that number.
Random Access: Now, let's say you have a box with 6 chocolates numbered from 0 to 5🔢. If you want the chocolate at slot 4, you don't need to go through all the chocolates one by one. You can directly pick chocolate number 4. That's what random access means - easy and quick access to any chocolate🍫 by its number.
Homogeneous Data: Picture another box of chocolates, but this time each chocolate is of the same flavor, let's say milk chocolate 🍫. No dark or white chocolates mixed in. This box is like an array with homogeneous data. It means all the chocolates (or elements) inside are of the same type. It's like having a box of chocolates where you know exactly what flavor to expect in each bite. 🍫🍫
Memory Efficiency: Now, imagine you have a big box📦 and you're storing chocolates in it. You start from one corner and keep filling up until you reach the other corner. There's no wasted space between chocolates 🍫 because they're all snugly packed together. This is what happens with arrays - they allocate memory in one continuous block, like chocolates in a box, reducing wasted space and making it memory efficient💡.
Types of Array
Declaration and Initialization of an array:
In a nutshell, here's how you work with one-dimensional arrays in Java:
Declaration: You can declare a one-dimensional array using either of these syntaxes
datatype[] arrayName; (e.g., int[] myArr;)
datatype arrayName[]; (e.g., int myArr[];)
Initialization: Initializing an array allocates memory for its elements. You can initialize a one-dimensional array like this
- arrayName = new datatype[size]; (e.g., myArr = new int[5];) - specifying the size is mandatory as it can't be modified later.
Declaration and Initialization in One Line: You can also declare and initialize the array in a single line.
datatype[] arrayName = new datatype[size]; (e.g., int[] myArr = new int[5];)
datatype arrayName[] = new datatype[size]; (e.g., int myArr[] = new int[5];)
Now that we've covered the basics and fundamentals,💻 it's time to take a deep dive into the exciting world of coding! 🚀So, buckle up and get ready to dive deep into the coding part! We'll be exploring🔍, experimenting 💪💡🌟.
Scenario's and Problems
Scenario: Imagine you're organizing a shelf to hold your favorite chocolate bars. You've got a shelf with five slots, each ready to hold a different kind of chocolate.
public class Arrays {
public static void main(String[] args) {
Arrays arr = new Arrays();
arr.myArrDemo();
System.out.println("Array elements: " + arr);
}
public void myArrDemo() {
int[] myArr = new int[5];
printArr(myArr);
myArr[0] =5;
myArr[1] =1;
myArr[2] =8;
myArr[3] =2;
myArr[4] =10;
myArr[2] =9;
myArr[5] =7;
}
public void printArr(int[] arr) {
int n = arr.length;
for(int i = 0;i < n; i++) {
System.out.print(arr[i]+ " ");
}System.out.println();
}
}
At first, your shelf is empty. Then, you start placing chocolates on it:
You place a chocolate labeled '5' in the first slot.
You add another chocolate labeled '1' in the second slot.
Now, you have chocolates labeled '5' and '1' on the shelf.
You add a chocolate labeled '8' in the third slot.
You add a chocolate labeled '2' in the fourth slot.
Finally, you place a chocolate labeled '10' in the last available slot.
Each time you add a chocolate, you take a step back to admire your collection. You print out the shelf to see the chocolates you've placed so far.
However, when you try to place a chocolate in the sixth slot (myArr[5] = 7;), you realize there's no slot left! This action results in an "ArrayIndexOutOfBoundsException" because you've exceeded the maximum number of slots available.
But your other chocolates remain on the shelf, ready to be enjoyed. 🍫📦
Scenario: Imagine you have two elements and you have to swap them
public class SwapElements{
public void swapNumber(int a, int b) {
System.out.println("Before swapping the elements: a= "+a+" b= "+b);
int temp = a;
a=b;
b=temp;
System.out.println("One way of swapping two numbers i.e. using the third elements:");
System.out.println("a= "+ a+ " ,b= "+b);
System.out.println("Another way of swapping two numbers i.e. without use of third elements:");
//at this point a = 3, b=2 becoz those got already swapped
a= a+b; //a= 3+2 a= 5,b= 2
b= a-b; //b= 5-2 a=5,b=3
a= a-b; //a = 5-3 a=2,b=3
System.out.println("a= "+ a+ " ,b= "+b);
}
Scenario: Let's you a list of elements in the array and you have to remove the even elements in the array and display only odd numbers.
public class RemoveEvenIntplaces {
public static void printArray(int[] arr) {
// this printArray is used to print the elements of the array using loop
for(int i =0; i< arr.length; i++) {
System.out.print(arr[i]+ " ");
}
System.out.println();
}
public static int[] removeEvenplaceInt(int[] arr) {
// this first part is used to count the number of odd elements in array
int temp = 0 ;
for(int i = 0; i < arr.length; i++) {
if(arr[i]%2 != 0) {
temp++;
}
}
// by using result array, adding the odd elements into array
int[] result = new int[temp];
int index =0;
for(int i=0;i < arr.length; i++) {
if(arr[i]%2 != 0) {
result[index] = arr[i];
index++;
}
}
return result;
}
public static void main(String[] args) {
//RemoveEvenIntplaces re = new RemoveEvenIntplaces();
int[] arr = {3,4,5,7,8,4,9,1};
System.out.println("Before removing the even elements");
printArray(arr);
int[] result = removeEvenplaceInt(arr);
System.out.println("After removing the even elements");
printArray(result);
}
}
Scenario: Imagine you have array with list of elements and you have to reverse the array.
public class ReverseArray {
public static void printArray(int[] arr) {
for(int i =0; i< arr.length; i++) {
System.out.print(arr[i]+ " ");
}
System.out.println();
}
public static void reverseArr(int[] arr, int start, int end) {
while(start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] myArr = {3,9,5,4,1,2};
System.out.println("Before swapping the array");
printArray(myArr);
reverseArr(myArr, 0, myArr.length-1);
System.out.println("After swapping the array");
printArray(myArr);
}
}
Subscribe to my newsletter
Read articles from Sri directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by