Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structures and Algorithms.

Similar presentations


Presentation on theme: "Data Structures and Algorithms."— Presentation transcript:

1 amel.ksibi@gmail.com Data Structures and Algorithms

2 Plan Introduction Arrays Algorithm analysis and complexity Linked Lists Stacks & Queues Trees 2 amel.ksibi@gmail.com

3 Introduction The large amount of information that is to be processed represents an abstraction of a part of reality. The information that is available to the computer consists of a selected set of data about the actual problem, namely that set that is considered relevant to the problem. The data represent an abstraction of reality in the sense that certain properties and characteristics of the real objects are ignored because they are irrelevant to the particular problem. 3 amel.ksibi@gmail.com

4 Introduction Representing information is fundamental to computer science. The primary purpose of most computer programs is not to perform calculations, but to store and retrieve information — usually as fast as possible. For this reason, the study of data structures and the algorithms that manipulate them is at the heart of computer science. This course is about helping you to understand how to structure information to support efficient processing. 4 amel.ksibi@gmail.com

5 Abstract Data Type An Abstract Data Type is typically defined as a Domain – i.e., a collection of values a set of operations that can be applied on the values in the domain Both these components together characterize an abstract data type. Some examples of ADTs: Boolean: The domain of the Boolean ADT is the set { true, false }. The operations on these values are negation, conjunction, disjunction, conditional, is equal to,… Integer: The carrier set of the Integer ADT is the set {..., -2, -1, 0, 1, 2,... }, The operations are addition, subtraction, multiplication, division, is equal to, … 5 amel.ksibi@gmail.com

6 Abstract Data Type Abstract data type: all details of implementation on a computer are ignored. Once an abstract data type is implemented on a computer, we call it a data type. Data type: An implementation of an abstract data type on a computer. Example: the Boolean ADT is implemented as the boolean type in Java, and the bool type in C++; the Integer ADT is realized as the int and long types in Java 6 amel.ksibi@gmail.com

7 Abstract Data Type Abstract data types are very useful for helping us understand the mathematical objects that we use in our computations, but, of course, we cannot use them directly in our programs. To use ADTs in programming, we must figure out how to implement them on a computer. Implementing an ADT requires two things: Representing the values in the carrier set of the ADT by data stored in computer memory, Realizing computational mechanisms for the operations of the ADT. 7 amel.ksibi@gmail.com

8 Data Structures and Algorithms Finding ways to represent carrier set values in a computer’s memory requires that we determine how to arrange data (ultimately bits) in memory locations so that each value of the carrier set has a unique representation.  Data structures Realizing computational mechanisms for performing operations of the type really means finding algorithms that use the data structures for the carrier set to implement the operations of the ADT.  Algorithms 8 amel.ksibi@gmail.com

9 Data structures and Algorithms Data structure is an arrangement of data in memory locations to represent values of the carrier set of an abstract data type. An algorithm is a finite sequence of steps for accomplishing some computational task. 9 amel.ksibi@gmail.com

10 Data structures and Algorithms Algorithm Analysis How to predict an algorithm’s performance How well an algorithm scales up How to compare different algorithms for a problem Data Structures How to efficiently store, access, manage data Data structures effect algorithm’s performance 10 amel.ksibi@gmail.com

11 Examples of data structures Example of data structure include: Arrays, Linked lists, Stacks, Queues, Trees, Graphs Data structures are applied in sorting, searching, graph algorithms, pattern matching, data compressing etc. 11 amel.ksibi@gmail.com

12 Data Structures categorization An important distinguishing characteristics of data structures is the manner in which they are organized. Data structures can be linear, hierarchical or unordered. Data structures are also categorized as static or dynamic depending on their allocation strategy. 12 amel.ksibi@gmail.com

13 Arrays 13 amel.ksibi@gmail.com

14 Data structure: Array An array is a sequential data abstraction, its name is a reference to an array. An array stores a sequence of values that are all of the same type. If we have N values, we can use the notation a[i] to refer to the ith value for any value of i from 0 to N-1. 14 amel.ksibi@gmail.com

15 Data structure: Array Creating and initializing an array Making an array in a Java program involves three distinct steps: o Declare the array name and type. o Create the array. o Initialize the array values. Using an array. Once we create an array, its size is fixed. A program can refer to the length of an array a[] with the code a.length. 15 amel.ksibi@gmail.com

16 Data structure: Array An array name refers to the whole array. If we assign one array name to another, then both refer to the same array, as illustrated in the following code fragment. int[] a = new int[N];... a[i] = 1234;... int[] b = a;... b[i] = 5678; // a[i] is now 5678. 16 amel.ksibi@gmail.com

17 Data structure: Array The array is handled by its reference, which indicates where the beginning of the array is stored in memory.  An array variable contains an address. 17 amel.ksibi@gmail.com

18 Data structure: Array The array is handled by its reference, which indicates where the beginning of the array is stored in memory.  An array variable contains an address. 18 amel.ksibi@gmail.com

19 Data structure: Array  Tableau [B@f665ab [B@f665ab  The variables S and T refer to the same address! 19 amel.ksibi@gmail.com

20 Data structure: Array 88 20 amel.ksibi@gmail.com

21 > [B@d16b31 [B@d16b34 > false  (two different addresses) Data structure: Array 21 amel.ksibi@gmail.com

22 Data Structure: Array Basic operations performed on an array: Search for a given item. Search for the (maximum / minimum ) item. Sort an array 22 amel.ksibi@gmail.com

23 Search: Necessary components to search an item: Array containing the elements. Length of the array. Item for which you are searching. After search completed: If item found, report “success” and return location in array. If item not found, report “failure.” Data Structure: Array 23 amel.ksibi@gmail.com

24 Search int seqSearch(int[] list, int listLength, int searchItem) { int loc; boolean found = false; for (loc = 0; loc < listLength; loc++) if (list[loc] == searchItem) { found = true; break; } if (found) return loc; else return -1; } 24 amel.ksibi@gmail.com

25 Search for the minimum int findMin(int[] list) { int i; int smallest; smallest = list[0]; for (i = 1; i < listLength; i++) if (list[i] < smallest) smallest = list[i]; return smallest ; } 25 amel.ksibi@gmail.com

26 Sorting a List Bubble sort Suppose list[0...n - 1] is an array of n elements, indexed 0 to n - 1. We want to rearrange (sort) the elements of list in increasing order. The bubble sort algorithm works as follows: In a series of n - 1 iterations, the successive elements, list[index] and list[index + 1], of list are compared. If list[index] is greater than list[index + 1], then the elements list[index] and list[index + 1] are swapped (interchanged). 26 amel.ksibi@gmail.com

27 Bubble Sort 27amel.ksibi@gmail.com

28 Bubble Sort 28 amel.ksibi@gmail.com

29 void bubbleSort(int list[], int listLength) { int temp; int counter, index; for (counter = 0; counter < listLength - 1; counter++) { for (index = 0; index < listLength - 1 – counter; index++) if (list[index] > list[index + 1]) { temp = list[index]; list[index] = list[index + 1]; list[index + 1] = temp; } Bubble Sort 29 amel.ksibi@gmail.com

30 Selection Sort Array is sorted by selecting element and moving it to its proper position. Algorithm finds position of smallest/biggest element and moves it to top of unsorted portion of list. Repeats process above until entire array is sorted. 30 amel.ksibi@gmail.com

31 Selection Sort 31amel.ksibi@gmail.com

32 Selection Sort 32 amel.ksibi@gmail.com

33 void selectionSort(int[] list, int listLength) { int index; int smallestIndex; int minIndex; int temp; for (index = 0; index < listLength – 1; index++) { smallestIndex = index; for (minIndex = index + 1; minIndex < listLength; minIndex++) if (list[minIndex] < list[smallestIndex]) smallestIndex = minIndex; temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp; } Selection Sort 33 amel.ksibi@gmail.com

34 Insertion Sort The insertion sort algorithm sorts the array by moving each element to its proper place. 34 amel.ksibi@gmail.com

35 Insertion Sort 35 amel.ksibi@gmail.com

36 Insertion Sort 36 amel.ksibi@gmail.com

37 Insertion Sort 37 amel.ksibi@gmail.com

38 void insertionSort(int[] list, int noOfElements) { int firstOutOfOrder, location; int temp; for (firstOutOfOrder = 1; firstOutOfOrder < noOfElements; firstOutOfOrder++) if (list[firstOutOfOrder] < list[firstOutOfOrder - 1]) { temp = list[firstOutOfOrder]; location = firstOutOfOrder; do { list[location] = list[location - 1]; location--; } while(location > 0 && list[location - 1] > temp); list[location] = temp; } } //end insertionSort Insertion Sort 38 amel.ksibi@gmail.com

39 Sequential Ordered Search public static int seqOrderedSearch(int[] list, int listLength, int searchItem) { int loc; //Line 1 boolean found = false; //Line 2 for (loc = 0; loc < listLength; loc++) //Line 3 if (list[loc] >= searchItem) //Line 4 { found = true; //Line 5 break; //Line 6 } if (found) //Line 7 if (list[loc] == searchItem) //Line 8 return loc; //Line 9 else //Line 10 return -1; //Line 11 else //Line 12 return -1; //Line 13 } 39 amel.ksibi@gmail.com

40 Binary Search Can only be performed on a sorted list. Uses divide and conquer technique to search list. If L is a sorted list of size n, to determine whether an element is in L, the binary search makes at most 2 * log 2 n + 2 key comparisons. (Faster than a sequential search.) 40 amel.ksibi@gmail.com

41 Binary Search Algorithm Search item is compared with middle element of list. If search item < middle element of list, search is restricted to first half of the list. If search item > middle element of list, search is restricted to second half of the list. If search item = middle element, search is complete. 41 amel.ksibi@gmail.com

42 Binary Search Algorithm Determine whether 75 is in the list. 42amel.ksibi@gmail.com

43 public static int binarySearch(int[] list, int listLength, int searchItem) { int first = 0; int last = listLength - 1; int mid; boolean found = false; while (first <= last && !found) { mid = (first + last) / 2; if (list[mid] == searchItem) found = true; else if (list[mid] > searchItem) last = mid - 1; else first = mid + 1; } if (found) return mid; else return –1; } //end binarySearch Binary Search Algorithm 43amel.ksibi@gmail.com

44 Data Structure: Array of objects When we create an array of objects, we do so in two steps: create the array, using the bracket syntax for array constructors; create each object in the array, using a standard constructor for each. 44 amel.ksibi@gmail.com

45 Data Structure: Array of objects 45 amel.ksibi@gmail.com

46 >Tableau: [LPersonne;@9ce743 > null Personne@9ce748 null Data Structure: Array of objects 46 amel.ksibi@gmail.com

47 >22 >24 Data Structure: Array of objects 47 amel.ksibi@gmail.com

48 public class Student { private String _name; private int _id; private float _grade; public Student() { _name = “none”; _id = 0; _grade =.0; } public Student(String name, int id, float grade) { _name = name; _id = id; _grade = grade;} } public class Course { private String _name; private Student[] _student; public Course(String name, int numOfStudents) { _name = name; _student = new Student[numOfStudents]; for (int i = 0; i < numOfStudents; i++) _student[i] = new Student(); // how to init name,id,grade for each obj } Application 1: 48 amel.ksibi@gmail.com

49 Application 2: using arrays (1/2) 49 package apparray1; import java.io.*; public class AppArray1 { int[] ids; String[] names; double[] avgs; public AppArray1(int nb) { ids=new int[nb]; names=new String[nb]; avgs=new double[nb]; } void setArrays(int nb) throws IOException { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); for (int i=0;i<nb;i++) { System.out.println("Please enter the data about student "+ i); System.out.print("name \t"); names[i]=b.readLine(); System.out.print("id \t"); ids[i]= Integer.parseInt(b.readLine()); System.out.print("average \t"); avgs[i]=Double.parseDouble(b.readLine()); } amel.ksibi@gmail.com

50 Application 2: using arrays (2/2) 50 void sortArrays(int nb) { double temp; int tempid; String tempname; int counter, index; int dim=nb-1; for (counter = 0; counter < dim; counter++) { for (index = 0; index < dim; index++) if (avgs[index] > avgs[index + 1]) { temp = avgs[index]; avgs[index] = avgs[index + 1]; avgs[index + 1] = temp; tempid = ids[index]; ids[index] = ids[index + 1]; ids[index + 1] = tempid; tempname = names[index]; names[index] = names[index + 1]; names[index + 1] = tempname; } void getSortedArrays(int nb) { for(int i=0; i<nb;i++) System.out.println(names[i]+" "+ ids[i]+" "+avgs[i]); } public static void main(String[] args) throws IOException { // TODO code application logic here AppArray1 app1=new AppArray1(5); app1.setArrays(5); app1.sortArrays(5); app1.getSortedArrays(5); } amel.ksibi@gmail.com

51 51 package apparray1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class Student{ String name; int id; double avg; } public class AppArrayClass { Student[] stds; public AppArrayClass(int nb) { stds=new Student[nb]; for(int i=0;i<nb;i++) stds[i]=new Student(); } public void initArrStd() throws IOException { BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); for(int i=0;i<stds.length;i++) { System.out.println("Please enter the data about student "+ i); System.out.print("name \t"); stds[i].name=b.readLine(); System.out.print("id \t"); stds[i].id= Integer.parseInt(b.readLine()); System.out.print("average \t"); stds[i].avg=Double.parseDouble(b.readLine()); } Application 2: using array of objects (1/2) amel.ksibi@gmail.com

52 52 void sortArrays() { Student temp; int counter, index; int dim=stds.length-1; for (counter = 0; counter < dim; counter++) { for (index = 0; index < dim; index++) if (stds[index].avg > stds[index + 1].avg) { temp = stds[index]; stds[index] = stds[index + 1]; stds[index + 1] = temp; } void getSortedArrays() { for(int i=0; i<stds.length;i++) System.out.println(stds[i].name+" "+ stds[i].id+" "+ stds[i].avg); } public static void main(String[] args) throws IOException { // TODO code application logic here AppArrayClass app1=new AppArrayClass(5); app1.initArrStd(); app1.sortArrays(); app1.getSortedArrays(); } } Application 2: using array of objects (2/2) amel.ksibi@gmail.com

53 Multidimensional Arrays Arrays with more than one index number of dimensions = number of indexes Arrays with more than two dimensions are a simple extension of two-dimensional (2-D) arrays A 2-D array corresponds to a table or grid one dimension is the row the other dimension is the column cell: an intersection of a row and column an array element corresponds to a cell in the table 53 amel.ksibi@gmail.com

54 Syntax for 2-D arrays is similar to 1-D arrays Declare a 2-D array of int s named table the table should have ten rows and six columns int[][] table = new int[10][6]; To initialize in the declaration: int [][] name = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; To access a component of a two-dimensional array: arrayName[index1][index2]; row position column position Multidimensional Arrays 54 amel.ksibi@gmail.com

55 Multidimensional arrays are implemented as arrays of arrays. Example: int[][] table = new int[3][4]; table is a one-dimensional array of length 3 Each element in table is an array with base type int. Access a row by only using only one subscript: table[0].length gives the length (4) of the first row in the array 012012 0 1 2 3 table[0] refers to the first row in the array, which is a one-dimensional array. Note: table.length (which is 3 in this case) is not the same thing as table[0].length (which is 4). Multidimensional Arrays 55 amel.ksibi@gmail.com

56 56 Initialization for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = row*col; Print for (row = 0; row < matrix.length; row++) { for (col = 0; col < matrix[row].length; col++) { System.out.printf( matrix[row][col]); } System.out.println(); } Multidimensional Arrays amel.ksibi@gmail.com

57 57 Exercise 1 (Sum by Row): Write code to output the sum of each row of a 2d matrix. Multidimensional Arrays amel.ksibi@gmail.com

58 58 Exercise 2 (Sum by Colunm): Write code to output the sum of each colunm of a 2d matrix. Multidimensional Arrays amel.ksibi@gmail.com

59 59 Exercise 2 (Max by Row): Write code to output the maximum element of each row in a 2d matrix. Multidimensional Arrays amel.ksibi@gmail.com

60 Ragged Arrays Ragged arrays have rows of unequal length each row has a different number of columns, or entries Ragged arrays are allowed in Java Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in the third row: int[][] b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4]; Initializing Ragged Arrays when declaration int [][] id= {{1,2},{3,4,5}, {6,7,8,9}}; 60 amel.ksibi@gmail.com

61 61 Exercise 1 (Is ragged?): Write a method to determine if an array is ragged. Ragged Arrays amel.ksibi@gmail.com


Download ppt "Data Structures and Algorithms."

Similar presentations


Ads by Google