Data Structures & Algorithms

# Data Structures & Algorithms

## Data Structures & Algorithms

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Data Structures & Algorithms Data Type Review Structured Data Types Abstraction Collection

2. Data & Variables • C# is a strong typed language • Actions on data is based on the type of data • Interaction between different types require conversion to a common type • All Data Types fall into 2 major groups that determine how the data can be accessed • Value Types • Reference Types

3. Data & Variables • Value Types • Uniquely identified by a variable name • Allocates storage at compile timemay also be initialized at compile time • Have 4 type sub-categoriessimple, enumerated, structured, nullable • When passed as a parameter a copy of the data is created automatically

4. Data & Variables High order Bit 100 - 1__ FF simplevalue data types: • Integral types unstructured • Signed: sbyte, short, int, long(-128…127) • Unsigned: byte, ushort, uint, ulong(0…255) • Floating point types • floating point: float, double • Special types • Boolean:bool(no numeric value, only TF) • Unicode characters: char

5. Data & Variables

6. Data & Variables Value Data Types are further sub-divided into • enum types Are User Defined (User Defined Data Type) • enum • Distinct type with named constants. • Each has an underlying type, which must be one of the eight integraltypes. • The set of values of an enum type is the same as the set of values of the underlying type.

7. Data & Variables Value Data Types are further sub-divided into • struct types Are User Defined • struct • Similar to class type • Represents a structure with data and function members. • Do not support user-specified inheritance • Implicitly inherit from type object. • Example: File w/ customers w/ addr & credit limit. Struct refers to the order, saved as .csv, can read data delimited by commas.

8. Data & Variables Value Data Types are further sub-divided into • nullable types • Extensions of all other value types with a null value • Declaration implied • Identified with the ? • I.E. int? is a type that can hold any 32 bit integer or the value null. (Compiler gives error otherwise if null is encountered)

9. Data & Variables • Reference Types • Allocates storage and is referenced by its storage address • Identified by variable names which are really the address (multiple identifiers possible) • May be initialized at compile time. (Without constructors, values set to zero)

10. Data & Variables Reference Data Types are further sub-divided into: Pre Defined • array types (fixed, immutable-treated as a value type at compile) User Defined • class types • interface types • delegate types

11. Data & Variables class types • Data structure that combines • state (fields) • actions (methods and other function members) • Dynamically create instances/ objects. (Static elements-occurs once, instances as many times as you want.) • Supports inheritance and polymorphismmechanisms whereby derived classes can extend and specialize a base class. (Polymorphism allows classes to be multiple data types w/ no problems. Inheritance enables base class to be extended to newer classes)

12. Data & Variables interface types • Defines a contract that can be implemented by class or structdata types. (Tells the definitions of what has to be done. ~names/signatures. A template for the development of your class or struct. Doesn’t say how things are implemented, only what it should be to work) • Can contain methods, properties, events, and indexers • Specifies classor struct members to be supplied that implement the interface. • Doesn’t provide member implementations • Abstract data type. Not instantitated.

13. Data & Variables arraytypes An array is a data structure that contains a number of variables that are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array.

14. Data & Variables delegate types Represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are object-oriented and type-safe – making native data types and all others usable. (Connects one-to-many processes. Delegate used in lieu of calls to individual methods. Like macros in MS Office. Combines names of methods used, and the order executed.)

15. The class Data Type classis a user defined data type consisting of a header and a body • Header Optional - attributes,  modifiers,partial Required - classidentifier Optional - type-parameter-list, class-base,type-parameter-constraints-clauses • Body Required -{} Optional - ;

16. The class Data Type class modifiers

17. The class Data Type • classaccessors

18. The class Data Type • class body contain members • function membersdefine actions done to the state of the class • data membersdefine the variables upon which the function members act.

19. class Example • Define a class, clockType, to implement the time of day in a program. • Time is represented as a set of three integers: one to represent the hours, one to represent the minutes, and one to represent the seconds. • Perform the following operations on the time: 1. Set the time. 2. Return the time. 3. Print the time. 4. Increment the time by one second. 5. Increment the time by one minute. 6. Increment the time by one hour. 7. Compare the two times for equality.

20. class Example • Some members of the classclockTypewill be private; others will be public. • Any member that needs to be accessed outside the class is declared public; any member that should not be accessed directly by the user should be declared private. • The user should be able to set the time and print the time. Therefore, the members that set the time and print the time should be declared public.

21. The class clockType has seven function members: • setTime • getTime • printTime • incrementSeconds • incrementMinutes • incrementHours • equalTime. • It has three data members: • hr • min • sec • The three data members—hr, min, and sec, are private to the class and cannot be accessed outside the class. • The seven function members can directly access the data members (hr, min, and sec).

22. public classclockType { private inthr, min,sec; public inthours //Hours property { get{return hr;} } public intminutes //Minutes property { get{return min;} } public intseconds //Seconds property { get{return sec;} }

23. public voidsetTime(intmHr, intmMin, intmSec) { if(0 <= mHr && mHr < 24) hr = hr = mHr else hr = 0; if(0 <= mMin && mMin < 60) min = mMin; else min = 0; if(0 <= mSec && mSec < 60) sec = mSec; else sec = 0; }

24. public voidgetTime(out mHr, outmMin, outmSec) { mHr = hr; //out passes by reference mMin = min; //~mMin “gets” from min msec = sec; } public voidprintTime() { Console.WriteLine(“The Time is {0:##}:{1:##}:{2:##}", hr,min,sec); //##mask } public voidincrementSeconds() { sec++; if(sec > 59) { incrementMinutes(); //add 1 to min, reset sec sec = 0; } }

25. public voidincrementMinutes() { min++; if(min > 59) { incrementHours(); min = 0; } } public voidincrementHours() { hr++; if(hr> 23) { hr= 0; } }

26. public boolequalTime(constclockType ref otherTime) { //const set clockType won’t be modified //clockType=myClock, otherTime=yourClock if( otherTime.hours == hr && otherTime.minutes== min && otherTime.seconds== sec ) return true; //otherTIme.hours =yourClock’s property else return false; // ==overridden }

27. Collections • Abstract concept – • Structured data type • No specific data type but defines a generic set of fields and methods. • Each object must be of the same type • Generic CRUD methods • Create • Read • Update • Delete

28. Collections • Collections can be • Linear • ie. Shopping list • Ordered each element follows the previous • Starting / Ending elements • Non-Linear • ie. Organization Chart • Structured but no specific order

29. Collections • Collections • Basic methods • Add() • Insert() • Remove() • Clear() • Contains() //searching algorithm • IndexOf() //specifies or retrieves specific place where object exists.

30. Collections • Collections • Accessing Collection Elements • Direct Access • Using a specific “Key” to access any element • //key value pairs • Sequential Access • Start at the beginning and continue, in order, to the end

31. Collections • Sequential Access Collections • Start at the beginning and continue, in order, to the end • Linear Lists • Unordered ~shopping lists • Ordered • Stacks (undordered) • Queues (unordered, but has priority queues) • Indexed collections • Hash Tables (direct access to element) • Dictionaries (uses key value pairs)

32. Collections • Hierarchical Collections • Trees • Each element is called a node • Each element may have a predecessor and/or successor along with the data being stored. • Parent Child relationship • Directory Structures • Binary Trees (2 choices at every parent, ends=leaves) • Heaps

33. Collections • Group Collections • Sets //takes groups of objs & combines in diff ways • An unordered group of unique elements • Methods – intersection, union • Graphs //more like network, edges connect each node • nodes and edges • Methods – traversals • ~Prob: driver finding most efficient path to deliver objs • Networks • Specialized graph where each edge is weighted

34. Collections - implementation publicclassCollection : CollectionBase { //Derived class: inheriting from CollectionBase publicvoidAdd(object item) { InnerList.Add(item); } publicvoid Remove(object item) { InnerList.Remove(item); } publicnewint Count() { returnInnerList.Count; } publicvoid Clear() { InnerList.Clear(); } }

35. Collections - implementation classCollectionProgram { staticvoid Main(string[] args) { Collection names = newCollection(); //not an array names.Add("John"); names.Add("Thomas"); names.Add("Ethan"); names.Add("Imani"); Console.WriteLine("Writing names added to ArrayList"); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); names.Remove("John"); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); names.Clear(); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); } staticvoidListNames(Collection col) { foreach (Object i in col) { Console.WriteLine(i); } } }

36. Generic Programming Allows you to create a method that will work for all data types. Use of a placeholder <> for the data type (capital T usually placed between<>) Data type is resolved at compile time C# = strongtyped language >>works only with datatypes that are the same. Can’t add int to float. That’s why it uses Implicit type conversions Writes method w/out knowing data type

37. The infamous swap( ) Problem – how many methods would you need to write to handle all of the integral data types? Answer: A lot. But by using generic definitions you only need one.

38. Declaration staticvoid swap <T> (ref T val1, ref T val2) { T temp; //T replaced w/ actual data type when swap is called temp = val1; val1 = val2; val2 = temp; }

39. Implementation Static void Main() { int x=100, y=200; Console.WriteLine( “x={0} y={1}“,x,y); swap<int> (ref x, ref y) //datatype known above Console.WriteLine( “x={0} y={1}“,x,y); }

40. A Stitch in Time Many times it is important to evaluate the efficiency of your code. The timing class will help answer this question. The .NET environment is unpredictable in terms of internal processes //inaccessible data in paging files Important to isolate timing for just your code.

41. The Timing Class namespace TimerClass { public class Timing { TimeSpanstartingTime, duration; public Timing() { startingTime = newTimeSpan(0); duration = newTimeSpan(0); //calculate distance between 2 TimeSpans } …

42. The Timing Class namespace TimerClass { public class Timing { public void StopTime() { duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime); } …

43. The Timing Class namespace TimerClass { public class Timing { public void StartTime() { GC.Collect(); //GC=garbage collection, automatic in C# //collects everything going on, cleans it up GC.WaitForPendingFinalizers(); //waits for process to be done ~500 microsec startingTime= Process.GetCurrentProcess().Threads[0].UserProcessorTime; } …

44. The Timing Class namespace TimerClass { public class Timing { public TimeSpan Result() { return duration; } } }

45. Timing Class Implementation classProgram { staticvoid Main(string[] args) { //Builds array, tracks process, outputs time it takes int[] nums = newint[100000]; BuildArray(nums); TimingtObj = newTiming(); tObj.StartTime(); DisplayNums(nums); tObj.StopTime(); Console.WriteLine( "Time (.NET):{0}", tObj.Result().TotalSeconds); }

46. Timing Class Implementation staticvoidBuildArray(int[] arr) { for (int i = 0; i < 100000; i++) arr[i] = i; } staticvoidDisplayNums(int[] arr) { for (int i = 0; i < 100000; i++) Console.WriteLine(arr[i]); } }

47. The Stopwatch Class usingSystem.Diagnostics; StopwatchswTimer;

48. The Stopwatch Class

49. The Stopwatch Class