Programming in C Comparison Sorting CSE 494 R

  • Slides: 6
Download presentation
Programming in C# Comparison (Sorting) CSE 494 R (proposed course for 459 Programming in

Programming in C# Comparison (Sorting) CSE 494 R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Comparison l Comparing two instances of a type has many of the same properties

Comparison l Comparing two instances of a type has many of the same properties and pitfalls as testing for equality. l Equality is generally more fussy. l Only two protocols for a type providing its own comparison: The IComparable interface l The > and < operators l

IComparable The IComparable<T> and IComparable interfaces allow for sorting or ordering of a collection.

IComparable The IComparable<T> and IComparable interfaces allow for sorting or ordering of a collection. l They are used in the Array. Sort method. l public interface IComparable <T>{ int Compare. To(T other); // -1 if this < other, 0 if this == other, 1 if this > other } 5. Compare. To(7) => -1 “World”. Compare. To(“Hello”) 32. Compare. To(8*4) => 0 => 1

IComparable Classes implementing IComparable are l Values types like Int 32, Double, Date. Time,

IComparable Classes implementing IComparable are l Values types like Int 32, Double, Date. Time, … l The class Enum as base class of all enumeration types l The class String l Defines a type to be is-a IComparable. l

The > and < operators l Value types that have a clear context independent

The > and < operators l Value types that have a clear context independent concept of less than and greater than should implement the < and > operators. l These are compiled statically into the code, making value types more efficient.

Programming in C# Comparison (Sorting) CSE 494 R (proposed course for 459 Programming in

Programming in C# Comparison (Sorting) CSE 494 R (proposed course for 459 Programming in C#) Prof. Roger Crawfis