Tuesday, June 7, 2016

Data-Structure discussion on Arrays

What is Array?

Ans: Array is the most commonly used data storage structure because they offer a convenient jumping-off place for introducing data structure and for seeing how object -oriented programming and data structure relate to one another.here we are not talking about and specific to to any language because array,s are built in most programming language.

We will also examine special kind of array,the ordered array in which data stored in ascending or descending order.This arrangement makes possible a fast way of searching for a data item;binary search.We will talk about different operation on arrays such as Insertion,Deletion and searching .

Note: nElement=Number of elements in the array.

Searching in unordered array:

public boolean find(long searchKey)
{
   int j;
for(j=0;j<nElements;j++)
{
   if(array[j]==searchKey)
   {
      if(j==nElements)
           return false;
      else
           return true;
 
   }
}
}

Insertion in unordered array :

public void insert(long value)
{
  array[nElements]=value;
  nElements++;
}

Insertion in Ordered Array:

public void insert(long value)
{
int j;
for(j=0;j<nElems;j++)
{
if(a[j] > value)
{
break;
}
for(int k=nElems; k>j;k--)
{
a[k] = a[k-1];
a[j]=value;
nElems++;
}
}
}

Searching in Ordered Array:

public int find(long searchKey)
{
int lowerBound=0;
int upperBound=nElems-1;
int currIn;

while(true)
{
currIn=(lowerBound+upperBound)/2;
if(a[currIn] == searchKey)
return true;
else if(lowerBound > upperBound)
return nElems;

else
{
if(a[currIn] < searchKey)
lowerBound=currIn+1;
else
{
upperBound=currIn-1;
}

}
}


}


Deletion in Ordered Array:

public boolean delete(long value)
{
int j=find(value);
if(j==nElems)
return false;
else
{
for(int k=j;k<nElems;k++)
{
a[k] =a[k+1];
nElems--;
return true;
}
}

}

No comments: