Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Data Structures and Algorithms

Lecture 2

Tanya M Smael
Department of Computer Science
Soran University
This session
• Arrays
• Recursion
Arrays
• It is a data structure designed to store a fixed-size sequential collection of
elements of the same type, i.e., it is a collection of variables of the same
type.
• An array stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Array Types

Arrays can be divided into the following four categories.


Single-dimensional arrays
Multidimensional arrays or rectangular arrays
Jagged arrays
Arrays
• An array is a sequence of elements.
Element index
• All elements of the same type.
0 1 2 3 4

1 2 5 7 8

Elements of an
array
Array of 5
elements
Array variable and creating Arrays
• datatype[] arrayname;
Example: Square brackets
double[] myList;

arrayname = new datatype[arraySize];


Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.
Declaring and Creating in One Step
• datatype[] arrayname = new
datatype[arraySize];
double[] myList = new double[10];
Data types supported
• Int
• Float
• Char
• String…
Length of arrays
• Once an array is created, its size is fixed. It cannot be changed.
You can find its size using arrayVariable.length

For example,
myList.length returns 10
Declaring, creating, initializing Using
the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Use of Arrays
• Below shown examples have only been able to hold one value at
a time
• Example:
int age = 20;
string name = “Orange”;
int id = 3;
• An Array allows you to use just one identifying name that refers
to lots of values
Assigning values
arrayName[position] = arrayValue;

Total
int[] age = new int[4]; number of
age[0] = 58; // first array array = size

age[1] = 24;
Index starts from zero
age[2] = 33;
age[3] = 41; // last (4th) array

Last index size-1


Declare, Set Array Size and Assign
Values in one line
• int[] age= new int[4] {1, 2, 3, 4};

Declaration Size of the array Assign values


Implementation – Retrieval(using for loop)
int[] array = { 100, 300, 500 };

for (int i = 0; i < array.Length; i++)


{
Console.WriteLine(array[i]);
}
Using foreach
int[] array = { 10, 30, 50 };

foreach (int value in array)


{
Console.WriteLine(value);
}
Sorting
• Sorting data (i.e., arranging the data into some particular order, such as
ascending or descending) is one of the most important computing
applications.
• (Will be discussed in the later sessions)
Search
• Large amounts of data stored in arrays.
• The process of locating a particular element value in an array is called
searching.
• The linear search method works well for small or unsorted arrays.
However, for large arrays, linear searching is inefficient.
• If the array is sorted, the high-speed binary search technique
can be used.
• The binary search algorithm eliminates half of the elements in the array
being searched after each comparison.
• (Will be discussed in the later sessions)
Multidimensional arrays or rectangular arrays

• A multi-dimensional array, also known as a rectangular array is an array


with more than one dimension. Eg., Two dimensional array
• A multi dimension array is declared as following:
string[,] mutliDimStringArray = new String[3,3];
• It can store type string of 3 rows and 3 columns.
• Same concept as single dimension array.
Structure of 2D array

• Structure of 2D array
Column 0 Column 1 Column 2

a[0][0] a[0][1] a[0][2]


Row 0

a[1][0] a[1][1] a[1][2]


Row 1

a[2][0] a[2][1] a[2][2]


Row 2
Initializing 2-D arrays
• The following is to show how to initialize 2 D arrays with a matrix of 3x2 and 2x2. The
first array can store 6 items and second array can store 4 items. Both of these arrays are
initialized during the declaration.
int[,] numbers = new int[3, 2] { { 1, 2 },
{3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2]
{ { “Apple", “Orange" }, { “Mango", “Banana" } };
• Now let's see examples of multi-dimensional static arrays where you are not sure of the
number of items of the array. The following code snippet creates two multi-dimensional
arrays with no limit.
int[,] numbers = new int[,] { { 1, 2 },
{ 3, 4 }, { 5, 6 } };
string[,] names = new string[,]
{ { “Apple", “Orange" }, { “Mango", “Banana" } };
We can also initialize the array items one item at a time. The following code
snippet is an example of initializing array items one at a time.

int[,] numbers = new int[3, 2];


numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
Accessing 2 D array elements
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6},
{4,8} };
int i, j;

for (i = 0; i < 5; i++)


{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0},{1}] ={2}", i, j,
a[i,j]);
}
}
Accessing 2 D array elements
Console.WriteLine(numbers[0,0]);
Console.WriteLine(numbers[0, 1]);
Console.WriteLine(numbers[1, 0]);
Console.WriteLine(numbers[1, 1]);
Console.WriteLine(numbers[2, 0]);
Console.WriteLine(numbers[2, 2]);
Jagged Arrays
• A Jagged Array is an array of an array in which the length of each array
index can differ.
int[][] jagArray = new int[3][];
• In the above declaration the rows are fixed (3) in size. But columns are not
specified as they can vary.
• Declaring and initializing jagged array.
int[][] jagArray = new int[3][];

jagArray[0] = new int[3];


jagArray[1] = new int[5];
jagArray[2] = new int[2];
• int[][] jagArray = new int[3][];

0 Int[ ]

Int[ ]
1

Int[ ]
2

On each index of jagged array another array reference is stored.


Jagged Arrays
jagArray[0] = new int[] { 3, 5, 7, };
jagArray[1] = new int[] { 1, 0, 2, 4, 6 };
jagArray[2] = new int[] { 1, 6 };

• You can also initialize the array upon declaration like this:

int[][] jagArray = new int[][]


{
new int[] { 3, 5, 7, 8},
new int[] { 1, 0, 2, 4, 6 },
new int[] { 1, 6 },
new int[] { 1, 0, 2, 4, 6, 45, 67, 78 }
};
System.Array - base class
Some Methods
• Sort(Array)
• Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.
• Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.
Properties
• Length
• Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.
• Rank
• Gets the rank (number of dimensions) of the Array.
Advanced - Collections
• ArrayList Dynamic arrays
• List<T>
Recursion
• Recursive method calls itself so many times until being satisfied.
• Recursive method has parameter(s) and calls itself with new parameter values.

• Recursion is a problem-solving approach in which a problem is solved using repeatedly applying


the same solution to smaller instances.
Or
• Recursion means a program will repeat certain steps or functions. 1 n0
you can use the "for loop", "do while" or if constructs. n! 
• Each instance to the problem has size.
n  (n  1)! n  1
• An instance of size n can be solved by putting together solutions of instances of size at most n-1.
• An instance of size 1 or 0 can be solved very easily.
Why recursion?
• In programming, recursion is a call to the same method from a method.
• Why write a method that calls itself?
• A method to solve problems by solving easier instance of the same problem.
• Does using recursion usually make your code faster?
No.
• Does using recursion usually use less memory?
No.
• Then why use recursion?
It sometimes makes your code much simpler!
Recursive Methods - Implementation
• A recursive method generally has two parts.
• A termination part that stops the recursion.
• This is called the base case (or anchor case).
• The base case should have a simple or trivial solution.
• One or more recursive calls.
• This is called the recursive case.
• The recursive case calls the same method but with simpler or smaller
arguments.
if ( base case satisfied ) {
return value;
}
else {
make simpler recursive call(s);
}
Recursion vs. Iteration
• Iteration can be more efficient
• Replaces method calls with looping
• Less memory is used (no activation record for each call)
• If a problem can be done easily with iteration, then do it with iteration.
• For example, Fibonacci can be coded with iteration or recursion, but the recursive
version is very inefficient (large call tree), so use iteration instead.
Use of Recursion
• Many problems are more naturally solved with recursion, which can provide elegant
solution.

• Fibonacci series
• Binary search
• Linear search
• Quick sort
• Merge sort
• Tree traversal
• Towers of Hanoi and many more…

• Conclusion: choice depends on problem and the solution context.


Lab Exercise
Next session
• Stack

You might also like