Arrays

Arrays

An array can be defined as a set of homogeneous data elements stored in contiguous memory locations.


Declaring an Array

  • datatype arrayname[]; Eg: int a[];
  • datatype[] arrayname; Eg: int[] a;

Creating an Array

  • To create blank array
    • arrayname = new datatype[size];
    • Eg: ar[] = new int[5];
  • To create filled array
    • arrayname = {value1, value2, ...};
    • Eg: ar = {3, 4, 5};



Array Initializer

An array initializer is a list of comma-separated values surrounded by braces.

Eg: {3, 4, 5, 2, 8}


Getting the size of the Array

We can get the size of the array using its length property.

Eg: int ar[] = new int[10];

int len = ar.length;

System.out.println(len);


Advantages of using Arrays

  • We can define as many variables as we want in a single statement.
  • We can access each element using the loop. This reduces the size of the program.

Disadvantages of using Arrays

  • Once an array is created we cannot change its size.

Difference between Linear Search and Binary Search

Linear Search

Binary Search

It searches all the elements in a sequential way

It checks the middle element and then according to its value it checks either on the left side or right side and leaves the other part

It can work on an unsorted array

It works on sorted arrays only

It is slower than binary search

It is faster than linear search



Difference between Bubble Sort and Selection Sort

Bubble Sort

Selection Sort

It compares adjacent elements, if they are not in order, swap them

It finds the smallest element of the array and swaps it with the first element

It is slower than selection sort because a number of swapping are to be done in each pass.

It is faster than bubble sort because only one swapping has to be done in each pass.

Post a Comment

0 Comments