Ir al contenido principal

Introduction to algorithms 3rd Edition

 2.3-6


INSERTION-SORT-2(A)
for j = 2 to A.length
    key = A[j]
    i = j-1
    r = BINARY-SEARCH-R'(A, A[j], 1, i)
    while i>r
        A[i+1] = A[i]
        i = i-1
    A[i+1] = key

/* returns p in [1..A.length] / A[p] = v1 and v1 <= v if v1 exists
 * returns 0 if v1 doesn't exist
 */
BINARY-SEARCH-R'(A, v, p, q)
if p>q
    return 0
if A[ (p+q)/2 ] <= v
    return max( (p+q)/2, BINARY-SEARCH-R'(A, v, (p+q)/2+1, q) )
else   // A[ (p+q)/2 ] > v
    return BINARY-SEARCH-R'( A, v, p, (p+q)/2-1 )

/* Iterative version
 */
BINARY-SEARCH-R'(A, v, p, q)
max_v : Integer
BEGIN
while p<=q
    if A[ (p+q)/2 ] <= v
        max_v = (p+q)/2
        p = (p+q)/2+1
    else   // A[(p+q)/2] > v
        q = (p+q)/2-1
if <=q
    return max_v
else
    return 0
END


2.3-7
Describe a O(n lg n)-time algorithm that, given a set S of n integers, and another integer x, determines whether or not exist 2 elements in S whose sum is exactly x

Hipótesis: Set S implementado como sorted array [1..length], BINARY-SEARCH definido como 0 cuando no existe el elemento buscado.

FIND-SUM-X-PAIR(S, x)
for j=1 to S.length-1
    p = BINARY-SEARCH(S, x-S[j], j+1, S.length)
    if p<>0
        return (j,p)

Comentarios

Entradas populares de este blog

Crear proyecto de frontend con Vite, React, Tailwind, Typescript y JSX

 ¿Cómo se crea un proyecto exclusivo de frontend con Vite, React, Tailwind, Typescript y JSX? ¡Absolutamente! Entiendo que quieres la guía completa para pasar de cero a tener un proyecto de frontend moderno, vacío y listo para ser llenado con tu código. A continuación, te proporciono un archivo de guía detallada que incluye todos los comandos necesarios para inicializar el proyecto, configurar Tailwind CSS, y los pasos clave para empezar a "poblarlo". Voy a generar un documento Markdown con la guía paso a paso, incluyendo los comandos de terminal y las modificaciones esenciales a los archivos de configuración. Guía: Creación de un Proyecto Frontend Puro (Vite, React, TypeScript, Tailwind) Este documento detalla el proceso para inicializar un proyecto de frontend vacío y optimizado, utilizando Vite como empaquetador, React como librería, TypeScript para tipado y Tailwind CSS para estilizado. 1. Inicialización del Proyecto con Vite Vite es la herramienta más rápida para emp...

Tokens V2

Tokens: Programme to discover tokens, where there are not. Now available at  https://puszcza.gnu.org.ua/projects/tokens/ This is Version 2, for  version 1, go here . Synopsis: use TokensV2; sub printFile; my @FORMAT = ( ['<Message Date=".*?" Time=".*?" DateTime=".*?" SessionID=".*?"><From>(?:<User FriendlyName=".*?"/>)+</From><To>(?:<User FriendlyName=".*?"/>)+</To><Text(?: Style=".*?")?>.*?</Text></Message>',   sub {     my $fh = $_[1];     my ($d, $t, $f, $s, $T) = $_[0] =~ m|<Message Date="(.*?)" Time="(.*?)" DateTime=".*?" SessionID=".*?">(<From>(?:<User FriendlyName=".*?"/>)+</From>)<To>(?:<User FriendlyName=".*?"/>)+</To><Text(?: Style="(.*?)")?>(.*?)</Text></Message>|;     my $F = join '<br />', ...

Perl Net::LDAP::SimpleServer

Adaptaciones sobre el módulo LDAP Server para Windows (Strawberry Perl) Lista de adaptaciones (continúa más abajo): - Relajación de condiciones de bind:     - Cuenta principal (principal account)     - Validación de contraseñas Ubicación del archivo: %Strawberry_Perl%\site\lib\net\ldap\SimpleServer\ProtocolHandler.pm CPAN: http://search.cpan.org/~russoz/Net-LDAP-SimpleServer-0.0.17/lib/Net/LDAP/SimpleServer.pm Código: package Net::LDAP::SimpleServer::ProtocolHandler; use strict; use warnings; # ABSTRACT: LDAP protocol handler used with Net::LDAP::SimpleServer our $VERSION = '0.0.17';    # VERSION use Net::LDAP::Server; use base 'Net::LDAP::Server'; use fields qw(store root_dn root_pw allow_anon); use Carp; use Net::LDAP::LDIF; use Net::LDAP::Util qw{canonical_dn}; use Net::LDAP::FilterMatch; use Net::LDAP::Constant (     qw/LDAP_SUCCESS LDAP_AUTH_UNKNOWN LDAP_INVALID_CREDENTIALS/,   ...