C # Sort selection with strings

Ok, I used this code to sort by purpose:

public void selectSort(int [] arr) { //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++) { if (arr[j] < arr[pos_min]) { //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; } } } 

but now I want to run the same algorithm in the list of strings.
How can I do that? This seems very inconvenient, and, as you need, additional loops will be required to compare several characters of different lines.

I tried a lot, but I could not think of anything.: /

Note: I know the selection of sorting is not very efficient. This is for educational purposes only. I'm not looking for alternative algorithms or classes that are already part of C # .;)

+5
source share
2 answers

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; } } } 
+8
source

The System.String class has a static method int Compare(string, string) , which returns a negative number if the first line is less than the second, zero if they are equal, and a positive integer if the first is more.

By "lesser" I mean that he precedes the other in the lexical order and more than he appears after the other in the lexical order.

So you can compare String.Compare(arr[j], arr[pos_min]) < 0 instead of arr[j] < arr[pos_min] for integers.

+2
source

Source: https://habr.com/ru/post/1238732/


All Articles