Está en la página 1de 45

INSTITUTO TECNOLÓGICO SUPERIOR DE LERDO

DEPARTAMENTO DE POSGRADO

“ ORDENAMIENTO DE DATOS ”

PRESENTA:
ERNESTO AMADOR FACIO MM1920006
JOSÉ RUBÉN TRUJILLO GARCÍA MM1920004

Docente: Dr. Hesner Coto

La excelencia académica al servicio de la sociedad

Ciudad Lerdo, Durango Viernes 11 de octubre del 2019


Introducción

Ordenar es simplemente colocar información de una manera especial


basándonos en un criterio de ordenamiento. El propósito principal de un
ordenamiento es el de facilitar las búsquedas de los registros del conjunto
ordenado. Un ordenamiento es conviene usarlo cuándo se requiere hacer
una cantidad considerable de búsquedas y es importante el factor tiempo.

Es importante destacar que existen diferentes técnicas de ordenamiento


como lo es:
• El Método Burbuja: Consiste en comparar pares de valores de llaves
• Método Selección: Consiste en encontrar el menor de todos los
elementos del arreglo e intercambiarlo
• Método Intercalación: Con el cual se combinan los sub-archivos
ordenados en una sola ejecución.

¿Qué es ordenamiento?

Es la operación de arreglar los registros de una tabla en algún orden


secuencial de acuerdo a un criterio de ordenamiento.

El ordenar un grupo de datos significa mover los datos o sus referencias


para que queden en una secuencia, tal que represente un orden, el cual
puede ser numérico, alfabético o alfanumérico, ascendente o
descendente.

El propósito principal de un ordenamiento es el de facilitar las búsquedas


de los registros del conjunto ordenado.
El método de ordenamiento conviene usarlo cuándo se requiere hacer una
cantidad considerable de búsquedas y es importante el factor tiempo.
Métodos de Ordenamiento

Debido a que las estructuras de datos son utilizadas para almacenar


información, para poder recuperar esa información de manera eficiente
es deseable que aquella esté ordenada. Existen varios métodos para
ordenar las diferentes estructuras de datos básicas.

En general los métodos de ordenamiento no son utilizados con frecuencia,


en algunos casos sólo una vez. Hay métodos muy simples de implementar
que son útiles en los casos en dónde el número de elementos a ordenar
no es muy grande (ej, menos de 500 elementos). Por otro lado, hay
métodos sofisticados, más difíciles de implementar pero que son más
eficientes en cuestión de tiempo de ejecución.

Los métodos sencillos por lo general requieren de aproximadamente n x


n pasos para ordenar n elementos.

Los métodos simples son: insertion sort (o por inserción directa) selection
sort, bubble sort, y shellsort, en dónde el último es una extensión al
insertion sort, siendo más rápido. Los métodos más complejos son el
quick-sort, el heap sort, radix y address-calculation sort. El ordenar un
grupo de datos significa mover los datos o sus referencias para que
queden en una secuencia tal que represente un orden, el cual puede ser
numérico, alfabético o incluso alfanumérico, ascendente o descendente.

Se ha dicho que el ordenamiento puede efectuarse moviendo los registros


con las claves. El mover un registro completo implica un costo, el cual se
incrementa conforme sea mayor el tamaño del registro. Es por ello que
es deseable evitar al máximo el movimiento de los registros. Una
alternativa es el crear una tabla de referencias a los registros y mover las
referencias y no los datos. A continuación, se mostrarán los métodos de
ordenamiento empezando por el más sencillo y avanzando hacia los más
sofisticados

La eficiencia de los algoritmos se mide por el número de comparaciones


e intercambios que tienen que hacer, es decir, se toma n como el número
de elementos que tiene el arreglo a ordenar y se dice que un algoritmo
realiza O(n2) comparaciones cuando compara n veces los n elementos, n
x n = n2.

Ejemplo de diferentes métodos de ordenamiento de datos como lo son:

ORDENAMIENTO DE BURBUJA

La Ordenación de burbuja (Bubble Sort en inglés) es un sencillo algoritmo


de ordenamiento. Funciona revisando cada elemento de la lista que va a ser
ordenada con el siguiente, intercambiándolos de posición si están en el orden
equivocado. Es necesario revisar varias veces toda la lista hasta que no se
necesiten más intercambios, lo cual significa que la lista está ordenada.
Este algoritmo obtiene su nombre de la forma con la que suben por la lista los
elementos durante los intercambios, como si fueran pequeñas "burbujas".
También es conocido como el método del intercambio directo. Dado que solo
usa comparaciones para operar elementos, se lo considera un algoritmo de
comparación, siendo el más sencillo de implementar.

burbuja
#include<stdio.h>
#include<conio.h>
int a[3]={3,2,1};
int i,j,aux,n=3;
void main(){
clrscr();
for(i=0;i<=n;i++){
for(j=0;j<n-1;j++){
if(a[j]>a[j+1]){
aux=a[j];
a[j]=a[j+1];
a[j+1]=aux;
}
}
}
for(i=0;i<3;i++)
{
printf("%d",a);
}
getch();
}
ORDENAMIENTO SHELL

El ordenamiento Shell (Shell sort en inglés) es un algoritmo de ordenamiento. El


método se denomina Shell en honor de su inventor Donald Shell. Su
implementación original, requiere O(n2) comparaciones e intercambios en el peor
caso. Un cambio menor presentado en el libro de V. Pratt produce una
implementación con un rendimiento de O(n log2 n) en el peor caso. Esto es mejor
que las O(n2) comparaciones requeridas por algoritmos simples pero peor que el
óptimo O(n log n). Aunque es fácil desarrollar un sentido intuitivo de cómo funciona
este algoritmo, es muy difícil analizar su tiempo de ejecución. El algoritmo Shell sort
mejora el ordenamiento por inserción comparando elementos separados por un
espacio de varias posiciones. Esto permite que un elemento haga "pasos más
grandes" hacia su posición esperada. Los pasos múltiples sobre los datos se hacen
con tamaños de espacio cada vez más pequeños. El último paso del Shell sort es un
simple ordenamiento por inserción, pero para entonces, ya está garantizado que los
datos del vector están casi ordenados.

shell
#include<stdio.h>
#include<conio.h>
int a[5];
int n=5;
void main()
{
int inter=(n/2),i=0,j=0,k=0,aux;
clrscr();
for (i=0; i<5; i++)
{
printf("INSERTA UN VALOR DEL INDICE %d", i);
scanf("%d",& a);
}
while(inter>0){
for(i=inter;i<n;i++)
{
j=i-inter;
while(j>=0) {
k=j+inter;
if(a[j]<=a[k]){
j--;
}
else{
aux=a[j];
a[j]=a[k];
a[k]=aux;
j=j-inter;
}
}
}
inter=inter/2;
}
for(i=0;i<5;i++)
{
printf("%d n",a);
getch();
}
}

ORDENAMIENTO POR INSERCION

El ordenamiento por inserción (insertion sort en inglés) es una manera muy


natural de ordenar para un ser humano, y puede usarse fácilmente para ordenar un
mazo de cartas numeradas en forma arbitraria. Requiere O(n²) operaciones para
ordenar una lista de n elementos.

Inicialmente se tiene un solo elemento, que obviamente es un conjunto ordenado.


Después, cuando hay k elementos ordenados de menor a mayor, se toma el
elemento k+1 y se compara con todos los elementos ya ordenados, deteniéndose
cuando se encuentra un elemento menor (todos los elementos mayores han sido
desplazados una posición a la derecha) o cuando ya no se encuentran elementos
(todos los elementos fueron desplazados y este es el más pequeño). En este punto
se inserta el elemento k+1 debiendo desplazarse los demás elementos.

iinserccion
#include<stdio.h>
#include<conio.h>
int a[4]={4,1,7,2};
int n=4;
int i,j,aux;
void main(){
clrscr();
for(i=1;i<n;i++)
{
j=i;
aux=a;
while(j>0 && aux<a[j-1])
{
a[j]=a[j-1];
j--;
}
a[j]=aux;
}
for(i=0;i<4;i++)
{
printf("%d",a);
}
getch();
}

ORDENAMIENTO POR SELECCIÓN

El ordenamiento por selección (Selection Sort en inglés) es un


algoritmo de ordenamiento que requiere O operaciones para ordenar
una lista de n elementos.

Su funcionamiento es el siguiente:

• Buscar el mínimo elemento de la lista


• Intercambiarlo con el primero
• Buscar el mínimo en el resto de la lista
• Intercambiarlo con el segundo

Y en general:
• Buscar el mínimo elemento entre una posición i y el final de la lista
• Intercambiar el mínimo con el elemento de la posición i
De esta manera se puede escribir el siguiente pseudocódigo para
ordenar una lista de n elementos indexados desde el 1:

para i=1 hasta n-1


minimo = i;
para j=i+1 hasta n
si lista[j] < lista[minimo] entonces
minimo = j /* (!) */
fin si
fin para
intercambiar(lista[i], lista[minimo])
fin para
seleccion
#include<stdio.h>
#include<conio.h>
int x[4]={1,4,8,6};
int n=4,j=0,i=0;
int temp=0,minimo=0;
void main(){
clrscr();
for(i=0;i<n-1;i++)
{
minimo=i;
for(j=i+1;j<n;j++)
{
if(x[minimo] > x[j])
{
minimo=j;
}
}
temp=x[minimo];
x[minimo]=x;
x=temp;
}
for(i=0;i<n;i++)
{
printf("%d",x);
}
getch();
}
ORDENAMIENTO POR INTERCALACIÓN

Es en la cual se combinan los sub-archivos ordenados en una sola


ejecución. Es un proceso bastante utilizado en sistemas de actualización.
También es la única forma que hay para el ordenamiento de archivos,
debido a la imposibilidad física de almacenarlos en memoria y a
limitaciones en el tiempo, por la cantidad de elementos a ordenar. Existen
diferentes tipos de intercalación, de los cuales se puede destacan:

• Intercalación Merge: Es el método más sencillo, pero menos


eficaz, consiste en colocar una lista detrás de la otra y luego
ordenarla. Este método no aprovecha la propiedad de que los
vectores A y B ya están ordenados, por ello debe recurrir
normalmente al sistema de mezcla el cual cosiste en comparar
los dos primeros elementos de los vectores (A y B) y enviar al
menor al tercer vector.

• Intercalación Simple: se tienen dos archivos ordenados y se


obtiene al final un solo archivo ordenado que contiene los
elementos de los dos archivos iniciales. para utilizar el método
se inicia con un vector de n posiciones. Se comienza con el
subíndice i, en la segunda posición incrementando en 1, el
elemento del subíndice del vector se elimina de la secuencia y se
reinserta en el vector en la posición adecuada.

Tipos de ordenamientos:

Los 2 tipos de ordenamientos óptimos según la estructura de datos a


utilizar son: los internos y los externos.
Los Internos: Son aquellos en que los valores a ordenar están en memoria
principal, por lo que se asume que el tiempo que se requiere para acceder
a cualquier elemento sea el mismo, este ordenamiento se aplica cuando
el conjunto de datos a clasificar es lo suficientemente pequeño.
Los Externos: Es cuando los datos a clasificar se encuentran almacenados
en archivos, en soportes de almacenamiento masivo (cintas o discos) el
tiempo de acceso a lectura y escritura influye en la eficiencia del
ordenamiento, por lo que se asume que el tiempo que se requiere para
acceder a cualquier elemento depende de la última posición accesada.
EJERCICIOS METODO DE ORDENAMIENTO

EJERCICIO 01

#include <stdio.h>
#define SIZE 7
void main(void) {
int vector[SIZE];
int j, i, temp;
printf("Introduce los %d valores para ordenar:\n", SIZE);
for(i=0; i<SIZE; i++) {
printf("%d: ", i+1);
scanf("%d", &vector[i]);
printf("\n");
}
/* se aplica el algoritmo de la burbuja */
for(i=0; i<(SIZE-1); i++) {
for (j=i+1; j<SIZE; j++) {
if(vector[j]<vector[i]) {
temp=vector[j];
vector[j]=vector[i];
vector[i]=temp;
}
}
}
printf("El vector ordenado es:\n");
for(i=0; i<SIZE ; i++) {
printf("%d ", vector[i]);
}
printf("\n");
}

EJERCIO 02

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void OrdenaBurbuja (float v[], int n)

int t, h, e;

for (h=1; h<n; h++)

for(e=0; e<n;e++)
{

if (v[e]>v[e+1])

v[e+1] = t;

v[e] = v[e+1];

t= v[e];

void ImprimirVector(float v[], int n)

int i;

for (i=0; i<n; i++)

printf("%f ", v[i]);

int main(int argc, char *argv[])

if(strcmp(argv[1], "burbuja")==0)

int n, i, m=2, o;

float *v;

n=argc-2;
v =(float *)malloc(n*sizeof(float));

for (i=0; i<n; i++)

v[i] = atof(argv[i+2]);

OrdenaBurbuja(v, n);

ImprimirVector(v, n);

system("PAUSE");

return 0;

Links de los Métodos de Ordenamiento más comunes:

Burbuja: https://youtu.be/P_xNb8nFgmA
Inserción: https://youtu.be/lYNyL0HuWSg
Selección: https://youtu.be/HVa2_UtXkCI
Capturas de Pantallas y Códigos:

#include "clase.h"
#include "LiquidCrystal.h"

void setup()
{
int tiempo1,tiempo2;
Serial.begin(9600);
LiquidCrystal lcd(9,8,7,6,5,4);
lcd.begin(20,4);

TArray datos;
Serial.println("El arreglo es:");
datos.Mostrar();

lcd.setCursor(0,0);
lcd.print("La suma es:"+(String)datos.Sumatoria());
delay(2000);
lcd.setCursor(0,1);
lcd.print("El prom es:"+(String)datos.Promedio());
delay(2000);
lcd.setCursor(0,2);
lcd.print("La mayor nota es:"+(String)datos.FindMax());
delay(2000);
lcd.setCursor(0,3);
lcd.print("La menor nota es:"+(String)datos.FindMin());
delay(2000);
lcd.clear();

lcd.setCursor(0,0);
lcd.print("Las notas son:"+(String)datos.Length());
delay(2000);
lcd.setCursor(0,1);
lcd.print("La nota en pos:"+(String)datos.Find());
delay(2000);
lcd.setCursor(0,2);
lcd.print("La moda es:"+(String)datos.Moda());
delay(2000);
lcd.clear();

tiempo1=millis();
datos.Burbuja();
tiempo2=millis();
lcd.setCursor(0,0);
lcd.print("Metodo burbuja");
lcd.setCursor(0,1);
lcd.print("El tiempo es:"+String(tiempo2-tiempo1)+"mS");
delay(2000);

datos.Restaurar();
tiempo1=millis();
datos.Seleccion();
tiempo2=millis();
lcd.setCursor(0,2);
lcd.print("Metodo seleccion");
lcd.setCursor(0,3);
lcd.print("El tiempo es:"+String(tiempo2-tiempo1)+"mS");
delay(2000);
lcd.clear();

datos.Restaurar();
tiempo1=millis();
datos.Insercion();
tiempo2=millis();
lcd.setCursor(0,0);
lcd.print("Metodo insercion");
lcd.setCursor(0,1);
lcd.print("El tiempo es:"+String(tiempo2-tiempo1)+"mS");
delay(2000);
datos.Restaurar();
tiempo1=millis();
datos.Shell();
tiempo2=millis();
lcd.setCursor(0,2);
lcd.print("Metodo shell");
lcd.setCursor(0,3);
lcd.print("El tiempo es:"+String(tiempo2-tiempo1)+"mS");
delay(2000);
}

void loop()
{

}
#include "LiquidCrystal.h"

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"

// When the display powers up, it is configured as follows:


//
// 1. Display clear
// 2. Function set:
// DL = 1; 8-bit interface data
// N = 0; 1-line display
// F = 0; 5x8 dot character font
// 3. Display on/off control:
// D = 0; Display off
// C = 0; Cursor off
// B = 0; Blinking off
// 4. Entry mode set:
// I/D = 1; Increment by 1
// S = 0; No shift
//
// Note, however, that resetting the Arduino doesn't reset the LCD, so
we
// can't assume that its in that state when a sketch starts (and the
// LiquidCrystal constructor is called).

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,


uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,


uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,


uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

LiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,


uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
{
init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);
}

void LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw,


uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)
{
_rs_pin = rs;
_rw_pin = rw;
_enable_pin = enable;

_data_pins[0] = d0;
_data_pins[1] = d1;
_data_pins[2] = d2;
_data_pins[3] = d3;
_data_pins[4] = d4;
_data_pins[5] = d5;
_data_pins[6] = d6;
_data_pins[7] = d7;

if (fourbitmode)
_displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;
else
_displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;

begin(16, 1);
}

void LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {


if (lines > 1) {
_displayfunction |= LCD_2LINE;
}
_numlines = lines;

setRowOffsets(0x00, 0x40, 0x00 + cols, 0x40 + cols);

// for some 1 line displays you can select a 10 pixel high font
if ((dotsize != LCD_5x8DOTS) && (lines == 1)) {
_displayfunction |= LCD_5x10DOTS;
}

pinMode(_rs_pin, OUTPUT);
// we can save 1 pin by not using RW. Indicate by passing 255 instead
of pin#
if (_rw_pin != 255) {
pinMode(_rw_pin, OUTPUT);
}
pinMode(_enable_pin, OUTPUT);
// Do these once, instead of every time a character is drawn for speed
reasons.
for (int i=0; i<((_displayfunction & LCD_8BITMODE) ? 8 : 4); ++i)
{
pinMode(_data_pins[i], OUTPUT);
}

// SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!


// according to datasheet, we need at least 40ms after power rises
above 2.7V
// before sending commands. Arduino can turn on way before 4.5V so
we'll wait 50
delayMicroseconds(50000);
// Now we pull both RS and R/W low to begin commands
digitalWrite(_rs_pin, LOW);
digitalWrite(_enable_pin, LOW);
if (_rw_pin != 255) {
digitalWrite(_rw_pin, LOW);
}

//put the LCD into 4 bit or 8 bit mode


if (! (_displayfunction & LCD_8BITMODE)) {
// this is according to the hitachi HD44780 datasheet
// figure 24, pg 46

// we start in 8bit mode, try to set 4 bit mode


write4bits(0x03);
delayMicroseconds(4500); // wait min 4.1ms
// second try
write4bits(0x03);
delayMicroseconds(4500); // wait min 4.1ms

// third go!
write4bits(0x03);
delayMicroseconds(150);

// finally, set to 4-bit interface


write4bits(0x02);
} else {
// this is according to the hitachi HD44780 datasheet
// page 45 figure 23

// Send function set command sequence


command(LCD_FUNCTIONSET | _displayfunction);
delayMicroseconds(4500); // wait more than 4.1ms

// second try
command(LCD_FUNCTIONSET | _displayfunction);
delayMicroseconds(150);

// third go
command(LCD_FUNCTIONSET | _displayfunction);
}
// finally, set # lines, font size, etc.
command(LCD_FUNCTIONSET | _displayfunction);

// turn the display on with no cursor or blinking default


_displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF |
LCD_BLINKOFF;
display();

// clear it off
clear();

// Initialize to default text direction (for romance languages)


_displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
// set the entry mode
command(LCD_ENTRYMODESET | _displaymode);

void LiquidCrystal::setRowOffsets(int row0, int row1, int row2, int row3)


{
_row_offsets[0] = row0;
_row_offsets[1] = row1;
_row_offsets[2] = row2;
_row_offsets[3] = row3;
}

/********** high level commands, for the user! */


void LiquidCrystal::clear()
{
command(LCD_CLEARDISPLAY); // clear display, set cursor position
to zero
delayMicroseconds(2000); // this command takes a long time!
}

void LiquidCrystal::home()
{
command(LCD_RETURNHOME); // set cursor position to zero
delayMicroseconds(2000); // this command takes a long time!
}

void LiquidCrystal::setCursor(uint8_t col, uint8_t row)


{
const size_t max_lines = sizeof(_row_offsets) / sizeof(*_row_offsets);
if ( row >= max_lines ) {
row = max_lines - 1; // we count rows starting w/0
}
if ( row >= _numlines ) {
row = _numlines - 1; // we count rows starting w/0
}

command(LCD_SETDDRAMADDR | (col + _row_offsets[row]));


}

// Turn the display on/off (quickly)


void LiquidCrystal::noDisplay() {
_displaycontrol &= ~LCD_DISPLAYON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::display() {
_displaycontrol |= LCD_DISPLAYON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turns the underline cursor on/off


void LiquidCrystal::noCursor() {
_displaycontrol &= ~LCD_CURSORON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::cursor() {
_displaycontrol |= LCD_CURSORON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}

// Turn on and off the blinking cursor


void LiquidCrystal::noBlink() {
_displaycontrol &= ~LCD_BLINKON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}
void LiquidCrystal::blink() {
_displaycontrol |= LCD_BLINKON;
command(LCD_DISPLAYCONTROL | _displaycontrol);
}
// These commands scroll the display without changing the RAM
void LiquidCrystal::scrollDisplayLeft(void) {
command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE |
LCD_MOVELEFT);
}
void LiquidCrystal::scrollDisplayRight(void) {
command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE |
LCD_MOVERIGHT);
}

// This is for text that flows Left to Right


void LiquidCrystal::leftToRight(void) {
_displaymode |= LCD_ENTRYLEFT;
command(LCD_ENTRYMODESET | _displaymode);
}

// This is for text that flows Right to Left


void LiquidCrystal::rightToLeft(void) {
_displaymode &= ~LCD_ENTRYLEFT;
command(LCD_ENTRYMODESET | _displaymode);
}

// This will 'right justify' text from the cursor


void LiquidCrystal::autoscroll(void) {
_displaymode |= LCD_ENTRYSHIFTINCREMENT;
command(LCD_ENTRYMODESET | _displaymode);
}
// This will 'left justify' text from the cursor
void LiquidCrystal::noAutoscroll(void) {
_displaymode &= ~LCD_ENTRYSHIFTINCREMENT;
command(LCD_ENTRYMODESET | _displaymode);
}

// Allows us to fill the first 8 CGRAM locations


// with custom characters
void LiquidCrystal::createChar(uint8_t location, uint8_t charmap[]) {
location &= 0x7; // we only have 8 locations 0-7
command(LCD_SETCGRAMADDR | (location << 3));
for (int i=0; i<8; i++) {
write(charmap[i]);
}
}

/*********** mid level commands, for sending data/cmds */

inline void LiquidCrystal::command(uint8_t value) {


send(value, LOW);
}

inline size_t LiquidCrystal::write(uint8_t value) {


send(value, HIGH);
return 1; // assume sucess
}
/************ low level data pushing commands **********/

// write either command or data, with automatic 4/8-bit selection


void LiquidCrystal::send(uint8_t value, uint8_t mode) {
digitalWrite(_rs_pin, mode);

// if there is a RW pin indicated, set it low to Write


if (_rw_pin != 255) {
digitalWrite(_rw_pin, LOW);
}

if (_displayfunction & LCD_8BITMODE) {


write8bits(value);
} else {
write4bits(value>>4);
write4bits(value);
}
}

void LiquidCrystal::pulseEnable(void) {
digitalWrite(_enable_pin, LOW);
delayMicroseconds(1);
digitalWrite(_enable_pin, HIGH);
delayMicroseconds(1); // enable pulse must be >450ns
digitalWrite(_enable_pin, LOW);
delayMicroseconds(100); // commands need > 37us to settle
}
void LiquidCrystal::write4bits(uint8_t value) {
for (int i = 0; i < 4; i++) {
digitalWrite(_data_pins[i], (value >> i) & 0x01);
}

pulseEnable();
}

void LiquidCrystal::write8bits(uint8_t value) {


for (int i = 0; i < 8; i++) {
digitalWrite(_data_pins[i], (value >> i) & 0x01);
}

pulseEnable();
}
#ifndef LiquidCrystal_h
#define LiquidCrystal_h

#include <inttypes.h>
#include "Print.h"

// commands
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80
// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00

// flags for display on/off control


#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00

// flags for display/cursor shift


#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00

// flags for function set


#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00
class LiquidCrystal : public Print {
public:
LiquidCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
LiquidCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

void init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,


uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);

void begin(uint8_t cols, uint8_t rows, uint8_t charsize =


LCD_5x8DOTS);

void clear();
void home();

void noDisplay();
void display();
void noBlink();
void blink();
void noCursor();
void cursor();
void scrollDisplayLeft();
void scrollDisplayRight();
void leftToRight();
void rightToLeft();
void autoscroll();
void noAutoscroll();

void setRowOffsets(int row1, int row2, int row3, int row4);


void createChar(uint8_t, uint8_t[]);
void setCursor(uint8_t, uint8_t);
virtual size_t write(uint8_t);
void command(uint8_t);

using Print::write;
private:
void send(uint8_t, uint8_t);
void write4bits(uint8_t);
void write8bits(uint8_t);
void pulseEnable();

uint8_t _rs_pin; // LOW: command. HIGH: character.


uint8_t _rw_pin; // LOW: write to LCD. HIGH: read from LCD.
uint8_t _enable_pin; // activated by a HIGH pulse.
uint8_t _data_pins[8];
uint8_t _displayfunction;
uint8_t _displaycontrol;
uint8_t _displaymode;

uint8_t _initialized;

uint8_t _numlines;
uint8_t _row_offsets[4];
};

#endif
#include "Arduino.h"
#include "clase.h"

TArray::TArray()
{
for(int i=0;i<250;i++)
{
nums[i]=random(1,250);
copi[i]=nums[i];
}
cnums=250;
}

void TArray::Restaurar()
{
for (int i=0;i<250;i++)
nums[i]=copi[i];
}

void TArray::Add(int num)


{
nums[cnums]=num;
cnums+=1;
}

int TArray::Mostrar()
{
for(int i=0;i<cnums;i++)
Serial.print((String)nums[i]+" ");
}

int TArray::Sumatoria()
{
int Sum = 0;
for (int i=0;i<cnums;i++)
Sum = Sum + nums[i];
return Sum;
}

float TArray::Promedio()
{
int Suma = 0;
for (int i=0;i<cnums;i++)
Suma = Suma + nums[i];
return (float)Suma/cnums;
}

int TArray::FindMax()
{
int Max=nums[0];
for(int i=0;i<cnums;i++)
if (nums[i]>Max)
Max=nums[i];
return Max;
}

int TArray::FindMin()
{
int Min=nums[0];

for(int i=0;i<cnums;i++)
if (nums[i]<Min)
Min=nums[i];
return Min;
}
int TArray::Length()
{
return cnums;
}

int TArray::Find()
{
int i=0;
int iFind=0;
int dato=10;
char band='F';
while((band=='F')&&(i<cnums))
{
if(nums[i]==dato)
{
band='V';
}
i++;
iFind=i;
}
return iFind-1;
}
int TArray::Moda()
{
int valor=0;
int cuantos=0;
for(int i=0;i<cnums;i++)
{
int contador=0;
for(int j=i;j<cnums;j++)
{
if(nums[i]==nums[j])
contador=contador+1;
}
if(contador>cuantos)
{
valor=nums[i];
cuantos=contador;
}

}
return valor;
}

void TArray::Burbuja()
{ int i,j,aux;
for(i=0; i<cnums; i++)
for(j=0; j<cnums; j++)

if(nums[j]>nums[j+1])
{
aux=nums[j];
nums[j]=nums[j+1];
nums[j+1]=aux;
}

void TArray::Seleccion()
{
int i,j,mi,aux;

for(i=0; i<cnums; i++)


{
mi=i;
for(j=i+1; j<cnums; j++)
{
if(nums[j]<nums[mi])
{
mi=j;
}
}
aux=nums[i];
nums[i]=nums[mi];
nums[mi]=aux;
}
}

void TArray::Insercion()
{
int i,j,pos,aux;
for(i=0; i<cnums; i++)
{
pos=i;
aux=nums[i];
while((pos>0)&&(nums[pos-1]>aux))
{
nums[pos]=nums[pos-1];
pos--;
}
nums[pos]=aux;
}
}

void TArray::Shell()
{
int temp;
for (int gap = cnums/2; gap > 0; gap =gap/2)

for (int i = gap; i < cnums; i ++)

for (int j = i-gap; j >= 0; j -= gap)


if (nums[j+gap]>=nums[j])
break;
else
{
temp=nums[j];
nums[j] = nums[j + gap];
nums[j+gap] = temp;
}
}
#ifndef clase_h
#define clase_h

class TArray
{
private:
int nums[250];
int copi[250];
int cnums;
public:
TArray();
void Add(int num);
void Restaurar();
int Mostrar();
int Sumatoria();
float Promedio();
int FindMax();
int FindMin();
int Length();
int Find();
int Moda();
void Burbuja();
void Seleccion();
void Insercion();
void Shell();
};
#endif
Conclusión.

Los métodos de ordenamiento de datos son muy útiles, ya que la forma


de arreglar los registros de una tabla en algún orden secuencial de
acuerdo a un criterio de ordenamiento, el cual puede ser numérico,
alfabético o alfanumérico, ascendente o descendente. Nos facilita las
búsquedas de cantidades de registros en un moderado tiempo, en modelo
de eficiencia. Mediante sus técnicas podemos colocar listas detrás de otras
y luego ordenarlas, como también podemos comparar pares de valores
de llaves, e intercambiarlos si no se encuentran en sus posiciones
correctas.

También podría gustarte