Click here to load reader

[email protected] Data Structures and Algorithms

Embed Size (px)

Citation preview

Advanced Data Structures

[email protected] Structures and AlgorithmsPlanIntroductionArraysAlgorithm analysis and complexityLinked ListsStacks & [email protected] 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 [email protected]

IntroductionRepresenting 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 [email protected] Data TypeAn 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, [email protected] Data TypeAbstract 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 [email protected] Data TypeAbstract 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 [email protected] Structures and AlgorithmsFinding ways to represent carrier set values in a computers 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

[email protected] structures and AlgorithmsData 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.

[email protected] structures and AlgorithmsAlgorithm AnalysisHow to predict an algorithms performance How well an algorithm scales upHow to compare different algorithms for a problemData StructuresHow to efficiently store, access, manage data Data structures effect algorithms performance

[email protected] of data structuresExample of data structure include: Arrays, Linked lists, Stacks, Queues, Trees, GraphsData structures are applied in sorting, searching, graph algorithms, pattern matching, data compressing etc.

[email protected] Structures categorizationAn 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.

[email protected]@gmail.comData structure: ArrayAn 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.

[email protected] structure: ArrayCreating and initializing an arrayMaking an array in a Java program involves three distinct steps: Declare the array name and type. Create the array. 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.

[email protected] structure: ArrayAn 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 [email protected] structure: ArrayThe array is handled by its reference, which indicates where the beginning of the array is stored in memory.

An array variable contains an address.

[email protected] structure: ArrayThe array is handled by its reference, which indicates where the beginning of the array is stored in memory.

An array variable contains an address.

[email protected] structure: ArrayTableau [B@f665ab [B@f665ab The variables S and T refer to the same address!

[email protected] structure: Array8

[email protected]> [B@d16b31 [B@d16b34 > false (two different addresses)

Data structure: [email protected] Structure: ArrayBasic operations performed on an array:Search for a given item.Search for the (maximum / minimum ) item.Sort an array

[email protected]: 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 [email protected] 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;}[email protected] for the minimumint 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 ;}[email protected] a ListBubble sortSuppose 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). [email protected] Sort

[email protected] Sort

[email protected] 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 [email protected] SortArray 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 [email protected] Sort

[email protected] Sort

[email protected] 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 [email protected] Sort

The insertion sort algorithm sorts the array by moving each element to its proper place.

[email protected] Sort

[email protected] Sort

[email protected] Sort

[email protected] 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 insertionSortInsertion [email protected] Ordered Searchpublic 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}[email protected] SearchCan 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 * log2n + 2 key comparisons. (Faster than a sequential search.) [email protected] Search AlgorithmSearch 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. [email protected] Search Algorithm

Determine whether 75 is in the list. [email protected] static int binarySearch(int[] list, int listLength, int searchItem){ int first = 0; int last = listLength - 1; int mid; boolean found = false; while (first searchItem) last = mid - 1; else first = mid + 1; } if (found) return mid; else return 1;} //end binarySearchBinary Search [email protected] Structure: Array of objectsWhen 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.

[email protected] Structure: Array of objects

[email protected]

>Tableau: [LPersonne;@9ce743> null Personne@9ce748 nullData Structure: Array of [email protected]

>22>24Data Structure: Array of [email protected] 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:[email protected] 2: using arrays (1/2)49package 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 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