Bifalgorithm post · Computer science one · Comparator Functions

What is a comparator function and how does it determine element order?

What is a comparator function and how does it determine element order? (Computer science one · Comparator Functions) — "A generic Quick Sort algorithm specifie…

Ideas in this flowchart

  • El Quick Sort genérico necesita una función comparadora para ordenar elementos de distintos tipos.
  • Quick Sort especifica cómo ordenar, pero no cómo se ordenan entre sí los elementos.
  • Debe determinar si dos elementos están ordenados, desordenados o son equivalentes para elegir sus particiones.
  • Los elementos pueden ser números, cadenas u objetos definidos por el usuario.
  • En C, la función comparadora determina el orden relativo de dos elementos.
  • Su firma es: int cmp(const void *a, const void *b);
  • Recibe dos punteros void * genéricos que apuntan a los elementos comparados.
  • La palabra clave const indica que los elementos no serán modificados.
  • Devuelve un entero que representa el orden relativo de los elementos.
  • Un valor menor que cero indica que a va antes que b.
  • Un valor igual a cero indica que a y b son equivalentes.
  • Un valor mayor que cero indica que a va después que b.
  • No se garantiza la magnitud del resultado: no tiene que ser −1 o +1.
  • strcmp() ofrece un contrato similar para comparar cadenas según su orden lexicográfico.
  • Strictamente, strcmp() no es una función comparadora genérica porque recibe const char *, no const void *.
  • Los punteros void * permiten generalizar la comparación para funciones genéricas de búsqueda y ordenamiento.
  • El lenguaje C compara tipos primitivos como int y double mediante operadores incorporados.
Feed/

What is a comparator function and how does it determine element order?

No cover

Channel

Computer science one

1 page

"A generic Quick Sort algorithm specifies how to sort elements, but it doesn’t specify how they are ordered. Essentially, Quick Sort needs to know when two elements, a and b, are in order, out of order, or equivalent in order to decide which partition each element goes in. However, it doesn’t “know” anything about the elements a and b themselves. They could be numbers, strings, or user-defined objects. A sorting algorithm still needs to be able to determine the proper ordering in order to sort. In C this is achieved through a comparator function, which is a function that is responsible for comparing two elements and determining their proper order.\n\nA comparator function has the following signature and behavior:\n\nint cmp(const void *a, const void *b);\n\nThe function takes two generic void * pointers which refer to the elements being compared. Moreover, the const keyword is used to indicate that no changes will be made to the elements. The function returns an integer indicating the relative ordering of the two elements: it returns something negative, < 0, if a comes before b; it returns zero if a and b are equal; and it returns something positive, > 0, if a comes after b. There is no guarantee on the value’s magnitude, so it does not necessarily return −1 or +1; it just returns something negative or positive.\n\nThis pattern was previously seen when comparing strings. The standard string library provides strcmp(), which has the same basic contract: it takes two strings and returns something negative, zero, or something positive depending on the lexicographic ordering of the two strings. Strictly speaking, however, strcmp() is not a comparator function because it is defined to take two const char * parameters, not const void * pointers. The C language and compiler know how to compare built-in primitive types like int and double using built-in comparison operators. To generalize the comparison operation, void * pointers are used so that general comparator functions can be written and used in generic searching and sorting functions."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.