lunes, 29 de septiembre de 2014

Encabalgar libros en CorelDraw con VBA

Programación en CorelDraw
En las primeras versiones de Corel, el lenguaje preferido era CorelScript.
A partir de la versión 12 (quizás antes), el lenguaje preferido pasó a ser VBScript con la librería VBA Corel. Para programar en VBScript es necesario conocer el Corel Object Model. Info en el mismo site que arriba, y en: http://apps.corel.com/partners_developers/csp/resources/dvba_pg.pdf

Public Sub BookDraw()
Dim var1$
ChDir "C:\Documents and Settings\Usuario\Mis documentos\casamiento diseño gráfico\libro firmas\preparación"
Open "orden de las paginas.txt" For Input Access Read As #256
Dim i As Integer
i = 1
Dim p As New Collection
Do While Not EOF(256)
Line Input #256, var1$
p.Add var1$
Loop
Close #256
Dim docNum As Integer
Dim upfit As Integer

upfit = (4 - p.Count Mod 4) Mod 4 + p.Count

docNum = 1

UserForm1.Label1.Caption = "0%"
UserForm1.show vbModeless

For i = 1 To upfit / 2
If i Mod 10 = 1 Then
ChDir "C:\Documents and Settings\Usuario\Mis documentos\casamiento diseño gráfico\libro firmas\preparación"
  FileCopy "plantilla.cdr", "copy preparación " + CStr(docNum) + ".cdr"
  Application.OpenDocument "copy preparación " + CStr(docNum) + ".cdr"
  ActiveDocument.ReferencePoint = cdrBottomLeft
  docNum = docNum + 1
Else
  ActiveDocument.AddPages 1
End If
Dim even, odd As Integer

If i Mod 2 = 0 Then
even = i
odd = upfit + 1 - i
Else
even = upfit + 1 - i
odd = i
End If

ActiveDocument.ActivePage.Name = "[" + CStr(even) + ", " + CStr(odd) + "]"

' inserto 1
ActiveDocument.ActivePage.ActiveLayer.Import p.Item(odd)
ActiveDocument.Selection.SizeHeight = 210 / 25.4
ActiveDocument.Selection.SizeWidth = 210 / 25.4
ActiveDocument.Selection.PositionX = 240 / 25.4
ActiveDocument.Selection.PositionY = 55 / 25.4

' inserto 2
If even > p.Count Then GoTo NUMERAR
ActiveDocument.ActivePage.ActiveLayer.Import p.Item(even)
ActiveDocument.Selection.SizeHeight = 210 / 25.4
ActiveDocument.Selection.SizeWidth = 210 / 25.4
ActiveDocument.Selection.PositionX = 20 / 25.4
ActiveDocument.Selection.PositionY = 55 / 25.4

NUMERAR:
' numero 1
ActiveDocument.ActivePage.ActiveLayer.CreateArtisticText 335 / 25.4, 48 / 25.4, "PÁGINA " & CStr(odd), , , "Arial", 12
' numero 2
ActiveDocument.ActivePage.ActiveLayer.CreateArtisticText 115 / 25.4, 48 / 25.4, "PÁGINA " & CStr(even), , , "Arial", 12

If i Mod 10 = 0 Then
ActiveDocument.Save
ActiveDocument.Close
End If

UserForm1.Label1.Caption = CStr(i * 200 / upfit) & "%"
DoEvents
Next i

' cierra documentos abiertos
If i Mod 10 <> 1 Then ' si el último loop no cerró el archivo por cambio 20-páginas
ActiveDocument.Save
ActiveDocument.Close
End If

End Sub

martes, 23 de septiembre de 2014

Herramientas de Programación

Repositorios concurrentes
Introducción a Git y GitHub
Software collaboration platform for free and private software Crear un repo y hacer el commit inicial por interfaz web
Libro sobre Git (2 recomendaciones), en formato online, PDF, etc.
Repositorio Git exclusivo de software libre

Un paseo por repositorios de software libre.
Hospedaje (hosting):
http://en.wikipedia.org/wiki/Comparison_of_open-source_software_hosting_facilities
http://en.wikipedia.org/wiki/GNU_Savannah
http://en.wikipedia.org/wiki/Gna!
Free Software collaboration platform compuesto únicamente de software libre http://savannah.gnu.org/maintenance/WhyChooseSavannah/
https://gna.org/
http://puszcza.gnu.org.ua/
Plataforma de desarrollo de OpenSource: www.CodeHaus.org
Freewares (consultar la licencia en cada caso): Planet Source


Cuestiones Legales
http://blog.codinghorror.com/pick-a-license-any-license/
https://wiki.debian.org/DFSGLicenses
http://opensource.org/
http://unlicense.org/
https://sfconservancy.org/overview/
http://www.fsf.org/

Software de revisión de código:
http://en.wikipedia.org/wiki/Comparison_of_revision_control_software



APIs - Librerías
http://alleg.sourceforge.net/
http://libcinder.org/
http://www.boost.org/
http://site.icu-project.org/



Canal de chat y comunidad de soporte de software libre

Directorio de software libre en Java
Directorio de software libre en Java
Software Open source de manejo de todas las capas de seguridad Java



Linux

http://www.linfo.org/index.html

Tour of the kernel source - tldp.org - Editar  Eliminar
[linuxkernel]

http://wiki.tldp.org/The_Linux_Kernel_HOWTO
http://www.tldp.org/LDP/lki/lki.pdf

Linux from scratch - linuxfromscratch.org - Editar  Eliminar
[linuxkernel - Instalar un Linux a partir de su código fuente.]

Reading the Linux Kernel Sources - wikiversity.org - Editar  Eliminar
[linuxkernel - Lugares por donde empezar a interpretar el código fuente de Linux.]

The Linux kernel - tue.nl - Editar  Eliminar
[núcleokernellinux - Some remarks on the Linux Kernel ]
Dentro del núcleo Linux 2.4 - wikilearning.com - Editar  Eliminar
[núcleokernellinux - Dentro del núcleo Linux 2.4 - por Tigran Aivazian Cómo funciona el núcleo Linux. URL Original (fuera de Wikilearning): http://es.tldp.org/Manuales-LuCAS/DENTRO-NUCLEO-LINUX/dentro-nucleo-linux-html/. (Publicado en D-Linuxnúmero 2).]
Building modules for a precompiled kernel - die.net - Editar  Eliminar
[insmodmodprobekernellinuxdriver - Cuando un módulo se compila contra un código fuente del núcleo diferente al que luego se va a insertar, es rechazado. Este control es con un string estático que se almacena en el módulo, e incluye tanto el código de versión (ej.: 2.6.39.4), como algunos parámetros de configuración importantes (los parámetros de compilación del núcleo, ej.: CONFIG_LOCALVERSION="-smp"). Si se está seguro de que las diferencias de versión no son importantes se puede forzar dicho string en concordancia con el del kernel. Búsqueda en Google: http://www.google.com/search?q=+Error+inserting+ath9k_htc+Invalid+module+format&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:es-AR:official&client=firefox-a#hl=es&safe=active&client=firefox-a&hs=6zB&rls=org.mozilla:es-AR%3Aofficial&sclient=psy-ab&q=Error+inserting+Invalid+module+format&oq=Error+inserting+Invalid+module+format&aq=f&aqi=g-L1g-mL1&aql=&gs_l=serp.3..0i19j0i5i19.4898.4898.0.5178.1.1.0.0.0.0.247.247.2-1.1.0...0.0.J6HRMNTIu88&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=35ede335b247a31e&biw=839&bih=774]
insmod: error inserting 'x.ko': -1 Invalid... - kerneltrap.org - Editar  Eliminar
[insmodmodprobekernellinuxdriver - Cuando un módulo se compila contra un código fuente del núcleo diferente al que luego se va a insertar, es rechazado. Este control es con un string estático que se almacena en el módulo, e incluye tanto el código de versión (ej.: 2.6.39.4), como algunos parámetros de configuración importantes (los parámetros de compilación del núcleo, ej.: CONFIG_LOCALVERSION="-smp"). Si se está seguro de que las diferencias de versión no son importantes se puede forzar dicho string en concordancia con el del kernel. Búsqueda en Google: http://www.google.com/search?q=+Error+inserting+ath9k_htc+Invalid+module+format&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:es-AR:official&client=firefox-a#hl=es&safe=active&client=firefox-a&hs=6zB&rls=org.mozilla:es-AR%3Aofficial&sclient=psy-ab&q=Error+inserting+Invalid+module+format&oq=Error+inserting+Invalid+module+format&aq=f&aqi=g-L1g-mL1&aql=&gs_l=serp.3..0i19j0i5i19.4898.4898.0.5178.1.1.0.0.0.0.247.247.2-1.1.0...0.0.J6HRMNTIu88&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=35ede335b247a31e&biw=839&bih=774]
Sata disk not identified during install - Linux - launchpad.net - Editar  Eliminar
[linuxdriversdrivercontroladorGNU/Linuxsataatadisco rígidohard diskkernelpci=nomsi - Cuando hay errores al inicio de Linux como: "unexpected IRQ trap at vector", no reconoce los discos rígidos SATA. Solución: pasar al kernel el parámetro de booteo: pci=nomsi]

How to get USB devices working under Linux - linux-usb.org - Editar  Eliminar
[linuxusbkeyboardmenuconfigkernel configkernel - Habilitar los dispositivos USB en Linux. Búsqueda en Google: http://www.google.com/search?q=make+menuconfig+usb+keyboard&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:es-AR:official&client=firefox-a]
Spase, el analizador semántico de códigos... - wikipedia.org - Editar  Eliminar
[linuxkernelsparcesemanthic parsersemanthic analysermixing pointerkernel address space - Sparce: dado un código fuente en C del núcleo de Linux, ayuda a nalizar cuestiones como: Manejo de punteros al espacio de usuario y al espacio delkernel, lockeos adquiridos por una función. El código debe ser anotado (agregarle marcas / etiquetas sobre los fragmentos de código a analizar).]
The Linux Tutorial - linux-tutorial.info - Editar  Eliminar
[linuxkerneltutorialmultiple choicetest yourself - El capítulo "Kernel basics" es igual a The Linux Kernel en "The LinuxDocumentation Project". Tiene tests para ver lo que aprendiste.]
Linux Device Drivers 3rd edition - Publisher... - makelinux.net - Editar  Eliminar
[linuxkerneltutorialbottom half handlersIRQinterrupt handlerinterrupttop half handlers - Programación de drivers enLinux, buena calidad]

JDBC - ODBC
Open Database Connectivity - Wikipedia, la enciclopedia libre
JDBC: Conectarse a una base de datos MS Access - Linea de Codigo
JDBC driver - Wikipedia, the free encyclopedia
JDBC-ODBC Bridge
java - JDBC ODBC Driver Connection - Stack Overflow
UCanAccess-A Pure Java JDBC Driver for Access
unixODBC


Redes Privadas Virtuales en Linux
Oleg Kolesnikov: www.cc.gatech.edu/~ok
Brian Hatch: clientes: bancos, farmacéuticos, instituciones educativas, desarrolladores de navegadores web, empresas .com
PPP sobre SSH (SSH no es sólo para línea de comando, sino que es para cualquier dato de texto o binario).
PPP sobre SSL/TLS
IPSec: protocolo desarrollado por IETF para dar seguridad al TCP/IP, que se ubica en la capa superior a éste. Componentes principales: IKE (Internet Key Exchange), AH (Authentication Header), ESP (Encapsulating Security Payload).
FreeS/WAN: cifrado oportunista
PPTP (point-to-point tunneling protocol)
VTun
cIPe
tinc
modelo OSI
Applied cryptography Bruce Schneier (John Wiley & sons 1996);
Handbook of Applied Cryptography Alfred J Menzes, Paul C. Van Oorschot y Scott Vanstone, CRC Press 1996;
IPX/SPX NetWare
autenticación
protocolos de autenticación estándar
enlaces WAN dedicados
PDH: plesiochronous digital hierarchy
SDH: synchronous digital hierarchy
CO: central office / Telephone exchange
dominio autenticado (§ Cómo autenticar nuestros usuarios móviles)
puerta de enlace - pasarela
DMZ
router / firewall - conmutador
registros DNS MX: sellección del servidor SMTP
acceso RAS
puerta de enlace VPN
VPN de administración dedicada
ancho de banda
solicitud de conexión entrante
Conexión RSDI (red digital de servicios integrados) / ISDN (integrated service digital network) connection
§ Host-Red
puerta de enlace VPN
autenticación de host
túnel VPN
conexión por marcación telefónica
conexión LAN
enlace inalámbrico
ADSL
§ Red-Red
Extranet
Capa de la pila OSI donde operan las puertas de enlace VPN
§ Ventajas
falseamiento IP
sniffing pasivo
pérdida de confidencialidad
inyección de paquetes
virus CodeRed y virus Nimda
informe anual CSI/FBI
coste total de propiedad (TCO)
infraestructura de marcación interna, circuito dedicado, Frame Relay, ATM
sniffing pasivo
www.vpnc.org
§ Comparación VPN con RAS
parámetros criptográficos
parámetros  ESA/AH
placas en serie multiport
guerra de marcación telefónica
§ Las VPN frente a las líneas dedicadas
líneas dedicadas, tipos de: T (T1, T3), E (europeas), líneas OC (OC3, OC12, OC48, OC192), enlaces inalámbricos (microondas, RF, satélites)
CPE (Customer Premise Equipemment)

Documentar una VPN: herramientas de descubrimiento
estrategia de administración de claves
DoS
salvaguardias de procedimiento y administrativas
Servicios de autenticación externos: SOCKS
Intentos de autenticación: mecanismos de respuesta a desafíos
cadena de autenticación
protocolo IPSec: RFC 2401, cifrado DES de 56 bits
Otros algoritmos de cifrado soportados por IPSec: la mayoría de las implementaciones soporta triple DES
OpenSSL: Entropía en la generación de números aleatorios para las claves: antes y después de la versión 0.9.6b
PGP
PKI
credenciales de los usuarios
ISP
firewall basado en hosts

stunnel
túnel seguro (individual)
Ejemplos de software no seguros per sé, que se pueden asegurar con PPP/SSH: VNC
Cryptanalysis of Microsoft's PPTP Authentication Extensions (MS-CHAPv2), Bruce Schneier y Mudge, 1999
Cryptographic Evaluation of IPSec, Niels Ferguson y Bruce Schneier, 2000
IPX / SPX, Appletalk
SOCKS5 / SOCKS
efecto de fusión TCP
Defense Message System (DMS)
HTTPS, SSL
RFC 1918 (intervalo de redes privadas)
SFTP, SCP (distribución de claves públicas)
Protocolo de encaminamiento IGP al uso (RIP, OSPF)
¿FreeS/WAN e IPSec pueden hablar? (§ Interoperatividad, Cap 2)
paquetes VPN para plataforma WinTel
httptunnel.com
protocolos y normas de estado
ftpd-ozone monkey.org/~dugsong
Linux Firewalls 2da edición Robert Ziegler 2002
(atención: los firewalls son para versiones específicas del kernel)
FWTK: Gauntlet, plug-gw: fwtk.org
IPF
IPChains, ip_masq_ftp
IPTables / Netfilter -> paquetes RELATED
IPFilter coombs.anu.edu.au/~avalon
Dante, firewall-proxy at circuit level: inet.no/dante
diferencia entre puertas de enlace de aplicación y puertas de enlace de aplicación individuales (=proxy)
T.REX, opensourcefirewall.com
¿qué es un registro de firewall?
DNS para distribución de la carga entre servidores ¿cómo?
ICMP
hub / conmutador (¿switch?)
filtros de paquetes del kernel Linux
NAT para uso: 1) no VPN, 2) VPN
Redes 10.x.y.z
enlaces / links
subred: 1) grande, 2) pequeña
intervalo IP
bloques CIDR
IOS de CISCO
"Link encap"
redes /32 / 255.255.255.255
etc/network/interfaces (Debian)
netstat -nr
tcpdump
Archivos de configuración: /proc/sys/net/ipv4/conf/all/...
¿Existe en la práctica una red donde todas las IPs, sean reales (LAN) o virtuales (VPN), estén en la misma red? (tras aplicar la máscara de red)... / ...que los host no conozcan puertas de enlace y cada host nuevo se sume de forma transparente?... / ...que haya 1 host encargado del enlace pero que actúe en nombre de cada dirección remota individual y no sea visto por los demás como puerta de enlace? O sea una VPN donde los hosts remotos puedan ser percibidos sin la noción de puerta de enlace.

Escanear documentos y aplicar OCR en Linux
Cómo extraer recursos (imágenes, íconos, audio) de un archivo binario de Visual Basic 6:
Los proyectos VB 6 se componen de los archivos de formularios (.frm) que en caso de tener datos binarios embebidos (imágenes, audio, etc., ej.: Un Formulario de ABM que tiene un botón "play" que reproduce una música .wav) dichos recursos se guardan en archivos binarios (.frx). Con este programa podemos extraer los recursos binarios del proyecto VB 6.

martes, 27 de mayo de 2014

Introduction to algorithms 3rd. edition - Excercises

Introduction to algorithms 3rd. edition
THOMAS H. CORMEN
CHARLES E. LEISERSON
RONALD L. RIVEST
CLIFFORD STEIN

Ejercicios
1.1-1 Organizar un padrón electoral; diseñar la carcasa de un coche.
1.1-2 Gastar los mínimos recursos (papel, nafta, horas de cierta maquinaria).
1.1-3 Lista doblemente enlazada: fortaleza: fácil inserción/borrado en cualquier lado. Debilidad: para llegar a un elemento se requiere acceder a todos los anteriores.
1.1-4 Que uno tiene que volver al punto de partida y el otro no. Que en uno los caminos son en cualquier sentido y en el otro hay que elegir un camino según el sentido.
1.1-5 Marcar un número de teléfono: sólo se admite el número exacto. Calcular las cantidades de comida de una dieta: se puede aproximar. Realizar una comida con una receta: las cantidades de cada ingrediente no tienen que ser exacta, los minutos de cocción, batido, etc. también se pueden aproximar.

1.2-1 Un programa de dibujo de gráficos / de manejo de un plotter: calcular los puntos de una curva, una calculadora de bolsillo: entre otras cosas tiene que interpretar las fórmulas y realizar las operaciones; programa de manejo de un lavarropas: el usuario pone el programa que quiere (una secuencia de etapas) y el lavarropas las ejecuta.
1.2-2
8 n^2 < 64 n lg n
n < 8 lg n
n <~ 40 (valor entero de lg n más cercano: 5 <=> n = 32)
1.2-3
100 n^2 < 2^n
lg (100 n^2) < lg 2^n
lg 100 + 2 lg n < n
lg 100 < n - 2 lg n
7 <~ n - 2 lg n
16 <~ n

Problemas

f(n) = [microseconds]
1 s = 1.000.000  µs
1 m = 1.000.000 * 60  µs



1  second
1 minute
1 hour
1 day
1 month
1 year
1 century
  lg n
 2^1.000.000
2^1.000.000*60
2^1.000.000*3.600
2^1.000.000*3.600*24
2^1.000.000*3.600*24*30
2^1.000.000*3.600*24*365
2^1.000.000*3.600*24*36.500
  \/¯n
 1.000.000^2






  n
 1.000.000






  n lg n
 ~ 2^16






  n^2
 1.000






  n^3
 100






  2^n
 ~ 20






  n!
 ~ 10





~ 17

1 second:
n lg n < 1.000.000
n lg n <~ 2^20 = 2^16 . 2^4  /// 16+4=20  y  lg 2^16=2^4
n <~ 2^16

n! < 1.000.000
n <~ 10

1 century:
n! < 1.000.000*3.600*24*36.500
n  <~ 17

1000000*3600*24*36500= 3.1536E+15
3153600000000000/2= 1.5768E+15
1576800000000000/3= 5.256E+14
525600000000000/4= 1.314E+14
131400000000000/5= 2.628E+13
26280000000000/6= 4.38E+12
4380000000000/7= 6.2571E+11
625714285714.286/8= 7.8214E+10
78214285714.2857/9= 8690476190
8690476190.47619/10= 869047619
869047619.047619/11= 79004329
79004329.004329/12= 6583694.08
6583694.08369408/13= 506438.006
506438.006438007/14= 36174.1433
36174.1433170005/15= 2411.60955
2411.6095544667/16= 150.725597
150.725597154169/17= 8.8662116
8.86621159730404/18= 0.49256731


Siguiente: página 22 (43/1313), Exercises
2.1-1
Using Figure 2.2 as a model, illustrate the operation of I NSERTION-SORT on the array A D h31;41;59;26;41;58i.



2.1-2 Rewrite the INSERTION-SORT procedure to sort into nonincreasing instead of non-decreasing order.
INSERTION-SORT .A/
1 for j = 2 to A.length
2   key = A[j]
3   // Insert j into the sorted sequence A[1..j-1].
4   i = j - 1
5   while i > 0 and A[i] < key
6     A[i - 1] = A[i]
7     i = i - 1
8   A[i + 1] = key



2.1-3
Consider the searching problem:
Input: A sequence of n numbers A =  (a 1 ;a 2 ;...;a n ) and a value v.
Output: An index i such that v = A[i] or the special value NIL if v does not appear in A.
Write pseudocode for linear search, which scans through the sequence, looking for v. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.
i = A.length
while i >= 0 and A[i]<>v
  i = i-1

Loop invariant: At the start of each iteration none of the elements at the right hand side are the searched one. And the searched element is either the one at the current iteration or any of the others at the left hand side, if it exists.
Initialization: It is true prior to the first iteration of the loop.
At the first loop, all of the array is at the left hand side. Only the current element is being looked at. The right hand side has no elements.
Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration.
At each iteration, which goes through downwards, the elements on the right hand side are all failed to the searched condition. And the left ones aren't yet tested.
Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
When the loop terminates, it was either because all the array stand at the right hand side or the last one examined was the searched one. The left hand side, consists of the elements not examined, if any.

2.1-4
Consider the problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an n+1-element array C. State the problem formally and write pseudocode for adding the two integers.

The binary sum of 2 numbers is:
For all the digits:
0 if both digits and the overflow is 0
1 if one and only one of the 3 is 1
0 if 2 of them are 1, and carrying overflow=1 since that
1 if the 3 are 1, and carrying overflow=1 either
The overflow is always taken from a less-significant-ward digit (hence the least one has not overflow).

overflow='0'
for i=0 to A.length  // A.length = B.length
  if overflow='0'
    if A[i]='0'
      C[i] = B[i]
    else
      if B[i]='0'
        C[i]='1'
      else
        C[i]='0'
        overflow='1'
  else
    if A[i]='0'
      if B[i]='0'
        C[i]='1'
        overflow='0'
      else
        C[i]='0'
    else
      C[i]=B[i]
C[i]=overflow    // exit loop with i = C.length = A.length+1

  

2.2-1 n^3
2.2-2 
// SELECTION-SORT

for i=0 to A.length-1
  jMin = i
  min = A[jMin]

  for j = i+1 to A.length
    if A[j] < min
      jMin = j
      min = A[jMin]
  A[jMin] = A[i]
  A[i] = min


Loop invariant: At the start of each outer iteration the elements at the left side are sorted.
Initialization: It is true prior to the first iteration of the loop.
At the first loop, all of the array is at the right side. The left side is void and since it has none element it's "sorted".
Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration.
At each outer iteration, the current element is exchanged with the least from the right side, taking part of the left side in the next iteration and being the least of the remainder means to be is order with the others.
Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
When the loop terminates, All the array is at the left side, except the last element which is the remainder and therefore is the greater of all, resulting in all the array being sorted.

// SELECTION-SORT

for i=0 to A.length-1      // c1  n
  jMin = i                 // c2  n-1
  min = A[jMin]            // c3  n-1

  for j = i+1 to A.length  // c4  sum(i=1..n) i
    if A[j] < min          // c5  sum(i=1..n-1) i
      jMin = j             // c6  sum(i=1..n-1) ti
      min = A[jMin]        // c7  "
  A[jMin] = A[i]           // c8  n-1
  A[i] = min               // c9  n-1

Best case: ti=0:  c1 n + (c2+c3+c8+c9)(n-1)+c4 n (n+1)/2 -1 + c5 n (n-1) /2=
= (c1+c2+c3+c8+c9) n - (c2+c3+c8+c9) + (c4 n^2 + c4 n) / 2 - 1 + (c5 n^2 -c5 n) / 2 =
= (c1+c2+c3+c8+c9) n - (c2+c3+c8+c9) + (c4+c5) n^2 / 2 + (c4 - c5) n / 2 - 1= 
= (c1+c2+c3+c8+c9+c4/2-c5/2) n - (c2+c3+c8+c9) + (c4+c5) n^2 / 2 - 1= a n^2 + b n + c
Worst case ti=i: c1 n + (c2+c3+c8+c9) (n-1) + c4 n (n+1) / 2 - 1 + (c5+c6+c7) n (n-1) / 2 =
= ... = (c1+c2+c3+c8+c9+c4/2-c5/2-c6/2-c7/2) n - (c2+c3+c8+c9) + (c4+c5+c6+c7) n^2 / 2 - 1= a n^2 + b n + c

2.2-3
average case: sum(i=0..n) i / n = [n (n+1) /2 -1]/n ~ n/2
worst case: n
O() notation:
average case: O(n) (like the average running time but coefficient omitted).
worst case: O(n)

2.2-4 To first check if the input already meets the supposed output so as to avoid any processing.

2.3-1
Using Figure 2.4 as a model, illustrate the operation of merge sort on the array
A = <3;41;52;26;38;57;9;49>

2.3-2
Rewrite the M ERGE procedure so that it does not use sentinels, instead stopping
once either array L or R has had all its elements copied back to A and then copying
the remainder of the other array back into A.




MERGE (A, p, q, r)
1. n1 = q - p + 1
2. n2 = r - q
3. let L[1..n1] and R[1..n2] be new arrays
4. for i = 1 to n1
5. L[i] = A[p + i - 1]
6. for j = 1 to n2
7. R[j] = A[q + j]
8. i = 1
9. j = 1
10. k = p
11. while i<=n1 and j<=n2
12. if L[i] <= R[j]
13. A[k] = L[i]
14. i = i + 1
15. else A[k] = R[j]
16. j = j + 1
17. // end if
18. k = k+1
19. // end while
20. while i<=n1
21. A[k] = L[i]
22. i=i+1
23. k=k+1
24. //end while
25. while j<=n2
26. A[k] = R[j]
27. j=j+1
28. k=k+1
29. //end while


MERGE-SORT (A;p;r)
1. if p < r
2. q = floor((p + r)/2)
3. MERGE-SORT (A;p;q)
4. MERGE-SORT (A;q + 1;r)


2.3-3
Use mathematical induction to show that when n is an exact power of 2, the solution of the recurrence
T(n)=
{
2 if n = 2 ;
2T(n/2) + n if n = 2^k , for k > 1
is T(n)= n lgn.





2.3-4



 


2.3-5

2.3-5 Referring back to the searching problem (see Exercise 2.1-3), observe that if the sequence A is sorted, we can check the midpoint of the sequence against v and eliminate half of the sequence from further consideration. The binary search algorithm repeats this procedure, halving the size of the remaining portion of the sequence each time. Write pseudocode, either iterative or recursive, for binary search. Argue that the worst-case running time of binary search is O(lg n).

BINARY-SEARCH(A, v)
p=1
q= A.length
MIENTRAS p<=q && v<> A[(p+q)/2]
  SI v < A[(p+q)/2]
    q= (p+q)/2-1
  SI v > A[(p+q)/2]
    p= (p+q)/2+1
SI p<=q
  DEVOLVER (p+q)/2
SI NO
  DEVOLVER NIL


BINARY-SEARCH-R(A,v,p,q)
SI p>q                                                // c1
  DEVOLVER NIL                                        // c2
SI v= A[(p+q)/2]                                      // c3
  DEVOLVER (p+q)/2                                    // c4
SI v < A[truncar((p+q)/2)]                            // c5
  DEVOLVER BINARY-SEARCH-R(A,v,p,truncar((p+q)/2)-1)  // T1: T(n/2-1), excluyente con T2
SI v > A[(p+q)/2]                                     // c6     // C=c1+c2+c3+c4+c5+c6
  DEVOLVER BINARY-SEARCH-R(A,v,truncar((p+q)/2)+1,q)  // T2: T(n/2-1), excluyente con T1


BINARY-SEARCH(A,v)
  DEVOLVER BINARY-SEARCH-R(A,v,1,A.length)