0% found this document useful (0 votes)
5 views

Ch 1- Intro to DS and Array (4)

The document provides an introduction to data structures and algorithms, emphasizing their importance in efficiently organizing and processing data. It covers various topics including the selection of appropriate data structures, the philosophy behind data structures, and a detailed revision of arrays, including their creation, access, and manipulation. The document also includes examples and code snippets to illustrate the concepts discussed.

Uploaded by

shaimaaabudayyeh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Ch 1- Intro to DS and Array (4)

The document provides an introduction to data structures and algorithms, emphasizing their importance in efficiently organizing and processing data. It covers various topics including the selection of appropriate data structures, the philosophy behind data structures, and a detailed revision of arrays, including their creation, access, and manipulation. The document also includes examples and code snippets to illustrate the concepts discussed.

Uploaded by

shaimaaabudayyeh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Faculty of Information Technology - Computer Science Department 1

Data Structures

Faculty of Information Technology - Computer Science Department 2


Chapter 1

Introduction to Data Structures

Faculty of Information Technology - Computer Science Department 3


Outline

 Introduction to Data Structures and Algorithms


 Importance of Data Structures and Algorithms
 Choosing the Right Data Structure
 Data Structure Philosophy
 Arrays – REVISION

Faculty of Information Technology - Computer Science Department 4


Introduction to Data Structures and Algorithms
 Data structure: is a programmatic way of organizing data so we can use it
efficiently (example: lists, stacks, …).

 Algorithm: a set of instructions that are executed in a certain order to


perform a specific task (example: sort, search, …)

 Algorithms are used to process data within data structures to perform the
intended tasks (for example add, delete, update, sort, and search)

 So ..
Algorithms + Data structures = A program

Faculty of Information Technology - Computer Science Department 5


Importance of Data Structures and Algorithms

 Computer applications are getting more complex and require the use of rich
and large data.
 Storing, processing, and searching the used data efficiently becomes
challenging.
 The choice of a suitable algorithm and a data structure can affect the

program performance and success.

Faculty of Information Technology - Computer Science Department 6


Choosing the Right Data Structure
 Efficiency:

 A solution is said to be efficient if it solves the problem within its resource


constraints (Space and Time).
 The cost of a solution is the amount of resources that the solution consumes.
 Select a DS as follows:
1. Analyze the problem to determine the resource constraints a solution must meet.
2. Determine the basic operations that must be supported.
3. Quantify the resource constraints for each operation.
4. Select the data structure that best meets these requirements.
Faculty of Information Technology - Computer Science Department 7
Data Structure Philosophy
Some Questions to Ask
 Are all data inserted into the data structure at the beginning, or are
insertions interspersed with other operations?
 Can data be deleted?
 Are all data processed in some well-defined order, or is random access
allowed?
DS Philosophy
 Each data structure has costs and benefits.
 Rarely is one data structure better than another in all situations.
 A data structure requires:
 Space for each data item it stores,
 Time to perform each basic operation,
 Programming effort. 8
Arrays – Revision
Arrays
Array Basics
Random-Access of Arrays
Types of Arrays
Creating Arrays
Accessing Array Elements
The length Property of Arrays
Using Loops with Arrays
Operations on Arrays
Two-Dimensional (2D) Arrays

Faculty of Information Technology - Computer Science Department


9
Arrays
 An array is a collection of similar-type elements which has contiguous memory
locations.

Faculty of Information Technology - Computer Science Department 10


Array Basics
 An array is a data structure where we store similar elements.
 An array has a length representing the number of elements in the array.
 The length of the array is fixed.
 Elements of an array can be accessed by their indices.
 Arrays are zero-based indexed, which means:
 The first element of the array is stored on the 0th index.
 The second element is stored on the 1st index.
 The element is stored on the index.

Faculty of Information Technology - Computer Science Department 11


Random-Access of Arrays

 Arrays are random access.


 This means that an element that is located at any index can be accessed immediately by
its index.
 This indicates that all the elements of the array can be accessed at the same speed.
 The speed of accessing the first element, at index 0, is equal to the speed of accessing the
last element, at index n-1.

Faculty of Information Technology - Computer Science Department 12


Types of Arrays
1. Single Dimensional Arrays (1D Arrays).
2. Two-Dimensional Arrays (2D Arrays).
3. Multi-Dimensional Arrays (nD Arrays).

Faculty of Information Technology - Computer Science Department 13


Creating Arrays
 To create an array, you need to declare it first.
 Array declaration implies:
 Assigning it to a variable.
 Defining the type of elements that it will store.
 Defining its length.
 We use the [] symbol to indicate that the corresponding variable is an array.
 For each dimension of the array, we use a separate [] symbol.
 For example:
 datatype[] variable; // creates a 1D array
 datatype[][] variable; // creates a 2D array
 datatype[][][] variable; //creates a 3D array

Faculty of Information Technology - Computer Science Department 14


Syntax
 An array declaration has the following syntax:
 datatype[] arrayName = new datatype[length];
 datatype[][] arrayName = new datatype[rows][columns];
 datatype[][][] arrayName = new datatype[1d Length][2d Length][3d Length];
 Note that array elements will be initialized to default values depending on the data type, as follows:
 Numeric arrays are initialized to the default value of 0 for each element.
 Boolean arrays are initialized to the default value false for each element.
 Character arrays are initialized to the default value space (' ') for each element.
 String arrays are initialized to the default value null for each element.

Faculty of Information Technology - Computer Science Department 15


Example
sDeclaring arrays:
 double [] dailyTemps; // elements are doubles
 String [] cdTracks; // elements are Strings
 boolean [] answers; // elements are booleans
 Auto [] cars; // elements are Auto references
 int [] cs101, bio201; // two integer arrays
Instantiating these arrays:
 dailyTemps = new double[365]; // 365 elements
 cdTracks = new String[15]; // 15 elements
 int numberOfQuestions = 30;
 answers = new boolean[numberOfQuestions];
 cars = new Auto[3]; // 3 elements
 cs101= new int[5]; // 5 elements
 bio201= new int[4]; // 4 elements
Faculty of Information Technology - Computer Science Department 16
Accessing Array Elements
 Arrays’ elements are accessed by their indices.
 To assign a value for an array element:
 arrayName[index] = value;
 To read or print the value that is stored in an array element:
 variable = arrayName[index];
 or, System.out.println(arrayName[index]);
 To store the value 5 in the 7th location of an array :
 a[6] = 5;
 To read the value that is stored at index 3:
 int x = a[3];
 To print the value that is stored in the 5th location:
 System.out.println(a[4]);
Faculty of Information Technology - Computer Science Department 17
Example
public class Main {
 In this example, we created the method
public static void printDefaults() {
int[] a = new int [4];
printDefaults() that declares four arrays: Boolean[] b = new boolean [4];
char[] c = new char[4];
a, b, c, and s. String[] s = new String[4];
System.out.println("a[0] = " + a[0]);
 The length of each array is 4. System.out.println("b[2] = " + b[2]);
System.out.println("c[1] = " + c[1]);
 That means that the indices in each array are System.out.println("s[3] = " + s[3]);
}
public static void main(String[] args) {
within the range [0, 3].
printDefaults();
 The method printDefaults() prints the }
}
default values that are stored in some locations
of each array. The output
Faculty of Information Technology - Computer Science Department
18
Example
public class Main {
 Create an array called “marks” of int datatype. public static void enterMarks (){
int[] marks = new int [5];
 Initialize its values to 90, 85, 95, 92, and 89. marks[0] = 90;
marks[1] = 85;
 Print these values stored in the array. marks[2] = 95;
marks[3] = 92;
 Look at the example to the right for further marks[4] = 89;

illustration. System.out.println("Mark #0:" + marks[0]);


System.out.println("Mark #1:" + marks[1]);
System.out.println("Mark #2:" + marks [2]);
System.out.println("Mark #3:" + marks [3]);
System.out.println("Mark #4:" + marks [4]);

}
public static void main(String[] args) {
enterMarks ();
} 19
Faculty of Information Technology - Computer Science Department
}
The length Property of Arrays
 In Java, arrays are objects.
 Each array has the length member variable (or property) that represents the number of
elements of the array.
 For example, the output of the following two lines of code is 5:
 int[] a = new int[5];
 System.out.println(a.length);
 Always remember, that the first element of the array has an index 0, and the last element
has index length-1.

Faculty of Information Technology - Computer Science Department 20


Using Loops with Arrays
public class Main {
 Loops can be used to access the elements of an array. public static void printMarks (){

 A for statement can be used to iterate from 0 to length–1 int[] marks ={95,75,42,68,57,88};

through the array elements. for(int i=0;i<marks.length;i++){

 Look at the example to the right. System.out.println(marks[i]);


}
 This way, we can iterate through the elements of the array }
public static void main(String[] args) {
regardless of how many elements are in the array.
printMarks ();
}
}

Faculty of Information Technology - Computer Science Department 21


Using Loops to Enter Array Elements
Import java.util.Scanner;
 It is more convenient to let the user enter the array public class Main {
public static void enterMarks (){
elements rather than writing them explicitly in the int[] marks = new int [5];

code (hardcoding). Scanner input = new Scanner(System.in);


for (int i = 0; i <= 4; i++){
 This allows your code to fit any problem of the same System.out.print("Enter mark #" + i + ": ");
marks[i] = input.nextInt ();
type, rather than writing code to each problem }

separately. for(int j=0;j<=4;j++){


System.out.println(marks[j]);
}
}
public static void main(String[] args) {
enterMarks ();
}
}
Faculty of Information Technology - Computer Science Department 22
Finding the Sum and Average of an Array’s Elements
 To find the sum of an array’s elements: public static int sumAvgMarks (){
 Initialize the sum variable to 0. int sum=0;
int[] marks ={55,35,95,66,78};
 Iterate through the array’s elements one by
one. for(int i=0;i<marks.length;i++){
 At each iteration, add the element indexed sum+=marks[i];
}
by the iteration number to the sum variable. return sum;
 When the loop exits, i.e., there are no more }
elements to iterate through, return the value public static void main(String[] args) {
int sum= sumAvgMarks ();
that is contained in the sum variable. double avg=(double)sum/5;
 To find the average: System.out.println("Sum = "+sum+", Average = "+avg); }
 use the sum() that we have just declared to }

find the sum of the array’s elements.


 Then, divide the sum by 5 (i.e. The length of
the array).
Faculty of Information Technology - Computer Science Department 23
The Maximum element of an Array
public static int findMax (){
 To find the maximum element of an array:
 Assume the first element is the maximum int[] numbers ={-15, 14, 0, -1, 41,-100};
element. int max = numbers [0];
 Iterate through the array’s elements starting for(int i=0;i<numbers.length;i++)
if (numbers[i]> max)
from the second element, i.e., index 1.
max =numbers [i];
 At each iteration, check if the array element return max;
at that index is greater than the maximum.
o If yes, then set the element at the current }
public static void main(String[] args) {
index as the maximum.
 Return the maximum value when the loop System.out.println("The Max = "+findMax());
}
exits. }

Faculty of Information Technology - Computer Science Department 24


Searching for a Value in the Array
 Searching for the value in an array implies public static int searchFor (int value){
checking whether the array contains that value.
int[] numbers ={1, 8, 9, 0, 6, 7,10};
 If the array contains that value, its index is
returned, otherwise, -1 is returned. for(int i=0;i< numbers.length;i++)
 To search for (or find) an element: if (numbers[i]==value)
return i;
 We iterate through all the array elements.
 At each iteration, we check whether the return -1;
}
element that is located in the current index public static void main(String[] args) {
equals the sought value.
System.out.println(“index of value 7 is at:”+
o If yes, we return the current index. searchFor (7));
o Otherwise, we make a new iteration. }
 If all the iterations are finished without
finding the value, then we return -1.

25
Faculty of Information Technology - Computer Science Department
Copying Arrays
 Suppose we want to copy the elements of an array to another array. We could try this
code:
int [] numbers ={1, 8, 9, 0, 6, 7, 10};
numbersBackup = numbers; // incorrect!

 Although this code compiles, it is logically incorrect! We are copying the numbers
object reference to the numbersBackup object reference. We are not copying the
array data.
 The result of this code is shown on the next slide.

Faculty of Information Technology - Computer Science Department 26


Copying Array References
int [] numbers ={1, 8, 9, 0, 6, 7, 10};
numbersBackup = numbers;
numbers
has the next effect:
numbersBackup

numbersBackup [0]  numbers [0] 0 1


numbersBackup [1]  numbers [1] 1 8
numbersBackup [2]  numbers [2] 2 9
numbersBackup [3]  numbers [3] 3 0
numbersBackup [4]  numbers [4] 4 6
numbersBackup [5]  numbers [5] 5 7
numbersBackup [6]  numbers [6] 6 10
Faculty of Information Technology - Computer Science Department 27
Copying Array Values

 Example: this code copies the values of all elements in an array named numbers to an
array named numbersBackup, both of which have previously been instantiated
with the same length:
for ( int i = 0; i < numbers.length; i++ )
{
numbersBackup[i] = numbers[i];
}
 The effect of this for loop is shown on the next slide.

Faculty of Information Technology - Computer Science Department 28


Copying Array Values

numbers
numbersBackup

numbers [0] 0 1
numbersBackup [0] 0 1
numbers [1] 1 8
numbers [2] numbersBackup [1] 1 8
2 9
numbersBackup [2] 2 9
numbers [3] 3 0
numbersBackup [3] 3 0
numbers [4] 4 6
numbersBackup [4] 4 6
numbers [5] 5 7
numbersBackup [5] 5 7
numbers [6] 6 10
numbersBackup [6] 6 10

Faculty of Information Technology - Computer Science Department 29


Changing an Array's Size
 An array's length instance variable is constant.
 That means arrays are assigned a constant size when they are
instantiated.
 To expand an array while maintaining its original values:

1. Instantiate an array with the new size and a temporary name.


2. Copy the original elements to the new array.
3. Point the original array reference to the new array.
4. Assign a null value to the temporary array reference.

Faculty of Information Technology - Computer Science Department 30


Expanding the Size of an Array
 This code will expand the size of the numbers array from 7 to 14 elements:
//instantiate a new array
int [] temp = new int [14];
// copy all elements from numbers to temp
for ( int i= 0; i <numbers.length; i++ )
temp[i] = numbers[i]; // copy each element
// point numbers to the new array
numbers = temp;
temp = null;

Faculty of Information Technology - Computer Science Department 31


Comparing Arrays for Equality
 To compare whether the elements of two arrays are equal:
 Determine if both arrays have the same length.
 Compare each element in the first array with the corresponding element in the
second array.
 To do this, we'll use a flag variable and a for loop.

Faculty of Information Technology - Computer Science Department 32


Comparing Arrays for Equality
 Consider that there are two int arrays, numbers1 and numbers2.
 The following code compares them for equality.
boolean isEqual = true;
if ( numbers1.length != numbers2.length )
isEqual = false;
else //sizes are equal
for ( int i = 0; i < numbers1.length; i++ )
if (numbers1[i] != numbers2[i]) // elements are not equal
{ isEqual = false;
break;
}
if (isEqual)
System.out.println(“arrays are equal”);
else
System.out.println(“arrays are not equal”);
Faculty of Information Technology - Computer Science Department 33
Two-Dimensional (2D) Arrays

 One can think of two-dimensional arrays (2D arrays)


int[][] marks = new int[5][3];
as matrices.

2 ndMark

3 rdMark
1 stMark
 In fact, matrices have many applications in
mathematics and our daily lives. 0 1 2
 Consider an example of five students, each student 0 0 0 0 1st Student

1 0 0 0 2nd Student
has three marks.
2 0 0 0 3rd Student
 In this case, we need to declare a 2D array with: marks=
4th Student
3 0 0 0
 5 rows, each row represents a student. 4 0 0 0 5th Student

 3 columns, each column represents a mark.


Faculty of Information Technology - Computer Science Department 34
Assigning Values to 2D Arrays
 In the following array, we specify a schedule for the employees as per days of the week:

String[][] schedule={{“Sat”, “Ahmad”},


{“Sun”, “Mohammed”},
{“Mon”, “Khalid”},
{“Tue”, “Omar”},
{“Wed”, “Yousef”},
{“Thu”, “Anas”},
{“Fri”, “Saleh”}};

Faculty of Information Technology - Computer Science Department 35


Accessing Elements of a 2D array
 To access the elements of a 2D array, we use the notation:
 arrayName[rowIndex][colIndex]
 Such that, rowIndex is the index of the row to access, and colIndex is the index of
the column we want to access.
 Let, be a 2D array that is declared as follows:
 int m[][] = new int[5][10];
 To assign a value to the element at row 3, column 7, we use:
 m[2][6] = 20;
 To print the value of the same element, we use:
 System.out.println(m[2][6]);
 To store the value of the same element in a memory variable, we use:
 int x = m[2][6];
Faculty of Information Technology - Computer Science Department 36
Looping in 2D Arrays
public static void printSchedule (){
 A 2D array of the size , that has rows and
String[][] schedule={{"Sat", "Ahmad"},
columns, can be looked at as an arrays, each of {"Sun", "Mohammed"},
length . {"Mon", “Khalid"},
{"Tue", "Omar"},
 To access the elements of a 2D array, say m[][], {"Wed", "Yousef"},
using loops, we need two nested loops: {"Thu", “Anas"},
{"Fri", "Saleh"}};
 The first loop is for the rows: the first index is
for (int i = 0; i < schedule.length; i++){
0 and the last is the length of the array, i.e., for (int j = 0; j < schedule[i].length; j++)
System.out.print(schedule[i][j] + "\t");
[0, m.length). System.out.println();
 The second loop is for the columns: it iterates }
}
the number of elements in each row. That is public static void main(String[] args)
[0, m[i].length). {
 The Example to the right shows how this is printSchedule ();
}
performed. }
Faculty of Information Technology - Computer Science Department 37

You might also like