Un instante de tiempo se da mediante una terna de números (h, m, s) — horas, minutos y segundos. Guardemos cada instante en una estructura con tres campos y ordenemos el arreglo de estructuras.
Comparación de instantes de tiempo. El instante ocurre antes que el instante si sus horas son menores. Si las horas son iguales, se comparan los minutos, y si coinciden tanto las horas como los minutos — los segundos. Tal comparación se llama lexicográfica: la siguiente clave se considera solo cuando todas las anteriores coinciden. El comparador para la función sort devuelve verdadero si debe ir antes que . La comparación debe ser estricta: para instantes iguales el comparador devuelve falso.
Ejemplo
Ordenemos los cuatro instantes de tiempo del ejemplo. Todas las horas son distintas, por lo que el orden queda determinado ya por la primera clave. Para mayor claridad, la columna derecha muestra el número de segundos desde el comienzo del día — estos números también crecen.
Si las horas coincidieran, el comparador pasaría a los minutos. Por ejemplo, para a = (13, 30, 30) y b = (13, 25, 59) las horas son iguales y los minutos cumplen 25 < 30, por lo que va antes que . En este caso los segundos ya no se comparan.
Implementación del algoritmo
Declaremos la estructura MyTime con los campos , y — horas, minutos y segundos. Guardamos los instantes de tiempo en el arreglo .
struct MyTime
{
int hour, min, sec;
};
MyTime lst[100];La función f es el comparador para la función sort. Devuelve verdadero si el instante debe ir antes que el instante , es decir, compara las ternas (\mathit{hour}, \mathit{min}, \mathit{sec}) lexicográficamente.
int f(MyTime a, MyTime b)
{Si las horas y los minutos coinciden, el orden lo determinan los segundos.
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;Si solo coinciden las horas, el orden lo determinan los minutos.
if (a.hour == b.hour) return a.min < b.min;En caso contrario, el orden lo determinan las horas.
return a.hour < b.hour;
}Parte principal del programa. Leemos los datos de entrada.
scanf("%d",&n);
for (i = 0; i < n; i++)
scanf("%d %d %d",&lst[i].hour,&lst[i].min,&lst[i].sec);Ordenamos los instantes de tiempo con la función sort y el comparador .
sort(lst, lst + n, f);Imprimimos los instantes de tiempo ordenados.
for (i = 0; i < n; i++)
printf("%d %d %d\n",lst[i].hour,lst[i].min,lst[i].sec);Implementación del algoritmo — asignación dinámica de memoria
El arreglo de instantes de tiempo se crea dinámicamente con el operador new después de leer y se libera con el operador delete[]. El constructor de la estructura con valores por defecto permite crear el arreglo sin inicializar explícitamente sus elementos.
#include <cstdio>
#include <algorithm>
using namespace std;
int i, n, h, m, s;
struct MyTtime
{
int hour, min, sec;
MyTtime (int hour = 0, int min = 0, int sec = 0) :
hour (hour), min(min), sec(sec) {};
} *lst;
int f(MyTtime a, MyTtime b)
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
int main(void)
{
scanf("%d",&n);
lst = new MyTtime[n];
for(i = 0; i < n; i++)
scanf("%d %d %d",&lst[i].hour,&lst[i].min,&lst[i].sec);
sort(lst,lst+n,f);
for(i = 0; i < n; i++)
printf("%d %d %d\n",lst[i].hour,lst[i].min,lst[i].sec);
delete[] lst;
return 0;
}Implementación del algoritmo — vector
Los instantes de tiempo se guardan en el vector , cuyo tamaño se establece con la función resize. Para ordenar el vector, a la función sort se le pasan los iteradores lst.begin() y lst.end().
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int i, n, h, m, s;
struct MyTime
{
int hour, min, sec;
};
vector<MyTime> lst;
int f(MyTime a, MyTime b)
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
int main(void)
{
scanf("%d",&n);
lst.resize(n);
for(i = 0; i < n; i++)
scanf("%d %d %d",&lst[i].hour,&lst[i].min,&lst[i].sec);
sort(lst.begin(),lst.end(),f);
for(i = 0; i < n; i++)
printf("%d %d %d\n",lst[i].hour,lst[i].min,lst[i].sec);
return 0;
}Implementación del algoritmo — comparador incorporado
En lugar de una función comparadora separada, la estructura define el operador operator<. La función sort llamada sin el tercer argumento compara los elementos precisamente con este operador, por lo que la llamada sort(\mathit{lst}, \mathit{lst} + n) dispone los instantes de tiempo en orden no decreciente.
#include <cstdio>
#include <algorithm>
using namespace std;
int i, n, h, m, s;
struct MyTtime
{
int hour, min, sec;
MyTtime (int hour = 0, int min = 0, int sec = 0) :
hour (hour), min(min), sec(sec) {};
int operator< (const MyTtime &a) const
{
if ((hour == a.hour) && (min == a.min)) return sec < a.sec;
if (hour == a.hour) return min < a.min;
return hour < a.hour;
}
} *lst;
int main(void)
{
scanf("%d",&n);
lst = new MyTtime[n];
for(i = 0; i < n; i++)
scanf("%d %d %d",&lst[i].hour,&lst[i].min,&lst[i].sec);
sort(lst,lst+n);
for(i = 0; i < n; i++)
printf("%d %d %d\n",lst[i].hour,lst[i].min,lst[i].sec);
delete[] lst;
return 0;
}Implementación del algoritmo — swap sort
Como n \le 100, se puede usar la ordenación por intercambio con complejidad O(n^2). Los elementos y se intercambian si no debe ir antes que , es decir, cuando !f(\mathit{lst}[i], \mathit{lst}[j]).
#include <stdio.h>
int i, j, n, h, m, s;
struct MyTime
{
int hour, min, sec;
};
MyTime lst[100];
int f(MyTime a, MyTime b) // return 1 if a < b
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
void swap(MyTime &a, MyTime &b)
{
MyTime temp = a; a = b; b = temp;
}
int main(void)
{
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d %d %d", &lst[i].hour, &lst[i].min, &lst[i].sec);
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (!f(lst[i], lst[j])) swap(lst[i], lst[j]);
for (i = 0; i < n; i++)
printf("%d %d %d\n", lst[i].hour, lst[i].min, lst[i].sec);
return 0;
}Implementación del algoritmo — qsort C
La implementación en C usa la función qsort. El comparador cmp devuelve un número negativo, cero o un número positivo según cuál de los instantes de tiempo sea anterior. Aquí la resta es segura: las horas, los minutos y los segundos no superan , por lo que no se produce desbordamiento.
#include <stdio.h>
#include <stdlib.h>
int n, i;
struct Time
{
int h, m, s;
};
struct Time t[100];
int cmp(const void* a, const void* b)
{
const struct Time* x = (const struct Time*)a;
const struct Time* y = (const struct Time*)b;
if (x->h != y->h) return x->h - y->h;
if (x->m != y->m) return x->m - y->m;
return x->s - y->s;
}
int main(void)
{
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d %d %d", &t[i].h, &t[i].m, &t[i].s);
qsort(t, n, sizeof(struct Time), cmp);
for (i = 0; i < n; i++)
printf("%d %d %d\n", t[i].h, t[i].m, t[i].s);
return 0;
}Implementación del algoritmo — Heap Sort
#include <stdio.h>
#define MAX 1001
int i, n;
struct MyTime
{
int hour, min, sec;
MyTime() {};
MyTime(MyTime &a) : hour(a.hour), min(a.min), sec(a.sec) {};
};
MyTime lst[MAX];
int f(MyTime a, MyTime b)
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
int left(int i)
{
return 2 * i;
}
int right(int i)
{
return 2 * i + 1;
}
void swap(MyTime &i, MyTime &j)
{
MyTime temp = i; i = j; j = temp;
}
// max - heap
void heapify(MyTime a[], int i, int n)
{
int largest = 0;
int l = left(i);
int r = right(i);
if (l <= n && f(a[i], a[l])) largest = l;
else largest = i;
if (r <= n && f(a[largest], a[r])) largest = r;
if (largest != i)
{
swap(a[i], a[largest]);
heapify(a, largest, n);
}
}
void BuildHeap(MyTime a[], int n)
{
for (int i = n / 2; i > 0; i--)
heapify(a, i, n);
}
void HeapSort(MyTime a[], int n)
{
BuildHeap(a, n);
for (int i = n; i >= 2; i--)
{
swap(a[1], a[i]);
heapify(a, 1, i - 1);
}
}
int main(void)
{
scanf("%d", &n);
for (i = 1; i <= n; i++)
scanf("%d %d %d", &lst[i].hour, &lst[i].min, &lst[i].sec);
HeapSort(lst, n);
for (i = 1; i <= n; i++)
printf("%d %d %d\n", lst[i].hour, lst[i].min, lst[i].sec);
printf("\n");
return 0;
}Implementación del algoritmo — MergeSort
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int i, n, h, m, s;
struct MyTime
{
int hour, min, sec;
MyTime() {};
MyTime(int hour, int min, int sec) :
hour(hour), min(min), sec(sec) {};
};
MyTime lst[100];
int f(MyTime a, MyTime b)
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
void merge(MyTime a[], int bleft, int bright, int cleft, int cright)
{
// a[bleft..bright] and a[cleft..cright] are merged into a[bleft..cright]
int i, left = bleft, len = cright - bleft + 1;
MyTime *res = new MyTime[len];
for (i = 0; i < len; i++)
{
if ((bleft > bright) || (cleft > cright)) break;
if (f(a[bleft], a[cleft])) res[i] = a[bleft], bleft++;
else res[i] = a[cleft], cleft++;
}
while (bleft <= bright) res[i++] = a[bleft++];
while (cleft <= cright) res[i++] = a[cleft++];
for (i = left; i < left + len; i++) a[i] = res[i - left];
delete[] res;
}
void mergeSort(MyTime a[], int left, int right)
{
if (left >= right) return;
int middle = (left + right) / 2;
mergeSort(a, left, middle);
mergeSort(a, middle + 1, right);
merge(a, left, middle, middle + 1, right);
}
int main(void)
{
scanf("%d", &n);
for (i = 1; i <= n; i++)
scanf("%d %d %d", &lst[i].hour, &lst[i].min, &lst[i].sec);
mergeSort(lst, 1, n);
for (i = 1; i <= n; i++)
printf("%d %d %d\n", lst[i].hour, lst[i].min, lst[i].sec);
return 0;
}Implementación del algoritmo — QuickSort
#include <cstdio>
#include <vector>
using namespace std;
int i, n, h, m, s;
struct MyTime
{
int hour, min, sec;
};
vector<MyTime> lst;
int f(MyTime a, MyTime b)
{
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
void swap(int &i, int &j)
{
int temp = i; i = j; j = temp;
}
int Partition(vector<MyTime> &m, int L, int R)
{
MyTime x = m[L];
int i = L - 1, j = R + 1;
while (1)
{
do j--; while (f(x, m[j]));
do i++; while (f(m[i], x));
if (i < j) swap(m[i], m[j]); else return j;
}
}
void QuickSort(vector<MyTime> &m, int L, int R)
{
int q;
if (L < R)
{
q = Partition(m, L, R);
QuickSort(m, L, q); QuickSort(m, q + 1, R);
}
}
int main(void)
{
scanf("%d", &n);
lst.resize(n);
for (i = 0; i < n; i++)
scanf("%d %d %d", &lst[i].hour, &lst[i].min, &lst[i].sec);
QuickSort(lst, 0, lst.size() - 1);
for (i = 0; i < n; i++)
printf("%d %d %d\n", lst[i].hour, lst[i].min, lst[i].sec);
return 0;
}Implementación en Java
import java.util.*;
class MyTime
{
int hour;
int min;
int sec;
public MyTime(int hour, int min, int sec)
{
this.hour = hour;
this.min = min;
this.sec = sec;
}
}
public class Main
{
public static class MyFun implements Comparator<MyTime>
{
public int compare(MyTime a, MyTime b)
{
if (a.hour == b.hour && a.min == b.min) return a.sec - b.sec;
if (a.hour == b.hour) return a.min - b.min;
return a.hour - b.hour;
}
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
ArrayList<MyTime> tm = new ArrayList<MyTime>();
for (int i = 0; i < n; i++)
tm.add(new MyTime(con.nextInt(), con.nextInt(), con.nextInt()));
Collections.sort(tm, new MyFun());
for (int i = 0; i < n; i++)
System.out.println(tm.get(i).hour + " " + tm.get(i).min + " " + tm.get(i).sec);
con.close();
}
}Implementación en Java — Heap sort
import java.util.*;
class MyTime
{
int hour;
int min;
int sec;
public MyTime(int hour, int min, int sec)
{
this.hour = hour;
this.min = min;
this.sec = sec;
}
}
public class Main
{
public static boolean f(MyTime a, MyTime b)
{
if (a.hour == b.hour && a.min == b.min) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
static int left(int i)
{
return 2 * i;
}
static int right(int i)
{
return 2 * i + 1;
}
static void swap(MyTime a[], int i, int j)
{
MyTime temp = a[i]; a[i] = a[j]; a[j] = temp;
}
//max - heap
static void heapify(MyTime a[], int i, int n) // n = size of a heap
{
int largest = 0;
int l = left(i);
int r = right(i);
if (l <= n && f(a[i],a[l])) largest = l;
else largest = i;
if (r <= n && f(a[largest],a[r])) largest = r;
if (largest != i)
{
swap(a, i, largest);
heapify(a, largest, n);
}
}
static void BuildHeap(MyTime a[], int n)
{
for (int i = n / 2; i > 0; i--)
heapify(a, i, n);
}
static void HeapSort(MyTime a[], int n)
{
BuildHeap(a, n);
for (int i = n; i >= 2; i--)
{
swap(a, 1, i);
heapify(a, 1, i - 1);
}
}
public static void main(String[] args) {
Scanner con = new Scanner(System.in);
int n = con.nextInt();
MyTime[] tm = new MyTime[n+1];
for (int i = 1; i <= n; i++)
tm[i] = new MyTime(con.nextInt(), con.nextInt(), con.nextInt());
HeapSort(tm, n);
for (int i = 1; i <= n; i++)
System.out.println(tm[i].hour + " " + tm[i].min + " " + tm[i].sec);
System.out.println();
con.close();
}
}Implementación en Java — MergeSort
import java.util.*;
class MyTime
{
int hour;
int min;
int sec;
public MyTime(int hour, int min, int sec)
{
this.hour = hour;
this.min = min;
this.sec = sec;
}
}
public class Main
{
public static boolean f(MyTime a, MyTime b)
{
if (a.hour == b.hour && a.min == b.min) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
static void merge(MyTime a[], int bleft, int bright, int cleft, int cright)
{
// a[bleft..bright] and a[cleft..cright] are merged
// into a[bleft..cright]
int i, left = bleft, len = cright - bleft + 1;
MyTime res[] = new MyTime[len];
for (i = 0; i < len; i++)
{
if ((bleft > bright) || (cleft > cright)) break;
if (f(a[bleft],a[cleft]))
{
res[i] = a[bleft];
bleft++;
}
else
{
res[i] = a[cleft];
cleft++;
}
}
while (bleft <= bright) res[i++] = a[bleft++];
while (cleft <= cright) res[i++] = a[cleft++];
for (i = left; i < left + len; i++) a[i] = res[i - left];
}
static void mergeSort(MyTime a[], int left, int right)
{
if (left >= right) return;
int middle = (left + right) / 2;
mergeSort(a, left, middle);
mergeSort(a, middle + 1, right);
merge(a, left, middle, middle + 1, right);
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
MyTime[] tm = new MyTime[n+1];
for (int i = 1; i <= n; i++)
tm[i] = new MyTime(con.nextInt(), con.nextInt(), con.nextInt());
mergeSort(tm, 1, n);
for (int i = 1; i <= n; i++)
System.out.println(tm[i].hour + " " + tm[i].min + " " + tm[i].sec);
System.out.println();
con.close();
}
}Implementación en Java — QuickSort
import java.util.*;
class MyTime
{
int hour;
int min;
int sec;
public MyTime(int hour, int min, int sec)
{
this.hour = hour;
this.min = min;
this.sec = sec;
}
}
public class Main
{
public static boolean f(MyTime a, MyTime b)
{
if (a.hour == b.hour && a.min == b.min) return a.sec < b.sec;
if (a.hour == b.hour) return a.min < b.min;
return a.hour < b.hour;
}
static void swap(MyTime a[], int i, int j)
{
MyTime temp = a[i]; a[i] = a[j]; a[j] = temp;
}
static int Partition(MyTime a[], int L, int R)
{
MyTime x = a[L];
int i = L - 1, j = R + 1;
while (true)
{
do j--; while (f(x,a[j]));
do i++; while (f(a[i],x));
if (i < j) swap(a, i, j); else return j;
}
}
static void QuickSort(MyTime a[], int L, int R)
{
if (L < R)
{
int q = Partition(a, L, R);
QuickSort(a, L, q);
QuickSort(a, q + 1, R);
}
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
MyTime[] tm = new MyTime[n+1];
for (int i = 1; i <= n; i++)
tm[i] = new MyTime(con.nextInt(), con.nextInt(), con.nextInt());
QuickSort(tm, 1, n);
for (int i = 1; i <= n; i++)
System.out.println(tm[i].hour + " " + tm[i].min + " " + tm[i].sec);
System.out.println();
con.close();
}
}Implementación en Python
Leemos el número de instantes de tiempo .
n = int(input())Un instante de tiempo se representa como una tupla (h, m, s). La lista contendrá todos los instantes de tiempo de entrada.
time = []Leemos los instantes de tiempo de entrada. Los añadimos a la lista .
for _ in range(n):
h, m, s = map(int, input().split())
time.append((h, m, s))Ordenamos los instantes de tiempo según el criterio dado.
time.sort()Imprimimos la respuesta.
for t in time:
print(*t)