Now that you have implemented sort sorting for arrays of integers, you want to generalize the solution for working with arrays of any type. This can be done using generics and the IComparable interface.
Generalizations allow us to parameterize functions with types. This is similar to how you can parameterize functions with values.
IComparable is an interface that gives us a function called CompareTo , which is a comparison operator. This operator works for all types that implement the IComparable interface, which includes both integers and strings.
// Forall types A where A is a subtype of IComparable public void selectSort<A>(A[] arr) where A : IComparable { //pos_min is short for position of min int pos_min,temp; for (int i=0; i < arr.Length-1; i++) { pos_min = i; //set pos_min to the current index of array for (int j=i+1; j < arr.Length; j++) { // We now use 'CompareTo' instead of '<' if (arr[j].CompareTo(arr[pos_min]) < 0) { //pos_min will keep track of the index that min is in, this is needed when a swap happens pos_min = j; } } //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur if (pos_min != i) { temp = arr[i]; arr[i] = arr[pos_min]; arr[pos_min] = temp; } } }
source share