Archivo categoría programacion
Tipos de variables en Java
Por Shaddar - java, programacion - 13 Diciembre 2009
Concepto de variable
Una variable es un contenedor de bits que representan a un valor. Se emplean para almacenar datos que pueden cambiar durante la ejecución de un programa. En función de los datos que almacenan se clasifican en:
- Variables primitivas: almacenan datos numéricos, valores lógicos o caracteres.
- Variables referenciadas: asociadas a objetos o instancias de una clase. Por ejemplo, para almacenar cadenas de caracteres se empleará una variable referenciada asociada a la clase String, para almacenar información sobre la fecha actual, otra asociada a la clase Date, etc. Se estudiarán más adelante.
Además de estos dos tipos de variables se estudiarán los arrays de variables primitivas y de variables referenciadas. Un array, como se verá en el tema correspondiente, es una variable referenciada asociada a la clase Object (clase madre de todos los objetos Java).
Se va a profundizar un poco más en el concepto de variable: como se ha comentado anteriormente, no es nada más que un contenedor de bits que representan a un valor. Ocurre lo siguiente:
- En el caso de variables primitivas, los bits representan un número entero que coincide con el valor de la variable, con lo que se va a trabajar a lo largo del programa. Por ejemplo, se tienen variables de tipo byte (utilizan 8 bits en memoria) que pueden almacenar números enteros comprendidos entre -128 y 127, de tipo int (utilizan 32 bits en memoria) para almacenar enteros entre, aproximadamente, -2150 millones y 2150 millones, de tipo float para números decimales, etc.

- En el caso de variables referenciadas o asociadas a objetos, los bits representan un numerajo que permite acceder al valor de la variable, es decir, al objeto, pero no es el valor u objeto en sí.

Todos los nombres empleados para hacer referencia a variables deben cumplir lo siguiente:
- Su primer carácter debe ser una letra, el símbolo del subrayado o el carácter dólar $.
- No son válidos las palabras reservadas de Java.
- No se admiten espacios en blanco.
- Son case-sensitive (sensibles a mayúsculas).
Aparte de estas normas conviene que los nombres de las variables indiquen qué dato almacenan con el fin de facilitar la lectura del programa y, por otra parte, si un nombre tiene más de dos palabras la primera letra de la primera palabra irá en minúscula, la primera letra de la segunda palabra en mayúscula, ídem con la tercera y así sucesivamente.
Ejemplo:
int miVariableEntera=100;
Variables primitivas
-
De tipo entero:
Son variables que almacenan números enteros. Se pueden dividir en los siguientes tipos:

| NOTA: el tipo de variable en que se almacena por defecto un numero entero es int. El valor por defecto asociado a cualquier variable entera no inicializada es 0. |
-
De tipo real o de coma flotante:
Son variables que almacenan datos numéricos con decimales. Se pueden dividir en los siguientes tipos:

| NOTA: el tipo de variable en que se almacena por defecto un numero decimal es double. El valor por defecto asociado a cualquier variable real no inicializada es 0.0. |
-
De tipo lógico o booleanas:
Son variables que almacenan dos posibles valores: true o false. No se corresponden con ningún valor numérico.
Ejemplo:
boolean tienesCalor=true;
| NOTA: el valor por defecto asociado a cualquier variable booleana no inicializada es false. |
-
De tipo char o de carácter:
Son variables que almacenan caracteres individuales (letra, numero, signo ?, etc…). El carácter que se inicializa debe ir entre apóstrofes o comillas simples ‘a’.
El código de caracteres empleado por Java es Unicode y recoge los caracteres de prácticamente todos los idiomas importantes del mundo (son unos 65.536). Los caracteres Unicode del alfabeto occidental corresponden a los primeros 256 enteros; es decir van desde [0, 255].
A cada carácter le corresponde unívocamente un número entero perteneciente al intervalo [0, 65536] o a [0, 255] si se trabaja sólo con el alfabeto occidental. Por ejemplo, la letra ñ es el entero 164. Más adelante se verá que el casting entre variables primitivas enteras y la variable char está permitido.
Ejemplo:
char miCaracter=’n';
char miCaracter1=110; (ídem antes, pero mediante el entero que le corresponde según Unicode)
char miCaracter2=’\u006E’; (ídem antes, pero según notación Unicode. La notación Unicode, en general, es así: \uXXXX siendo X un dígito o cifra fundamental del sistema de numeración hexadecimal (0,1,2,…,9,A,B,…,F))
Asociado a este tipo de variable se tienen las secuencias de escape. Se emplean para representar caracteres especiales (por ejemplo, unas comillas dentro de una instrucción que exige una cadena entrecomillada) y caracteres no imprimibles como el tabulador, salto de línea, etc. Van precedidos de la contrabarra. Algunos de ellos se detallan en la tabla siguiente:

| NOTA: el valor por defecto asociado a cualquier variable char no inicializada es ‘\u0000′ |
Ejemplo: todos los códigos de este tema se guardarán en c:\cursojava\tema2

Por consola:
Comienza programa
El valor de tengoCalor es true
El valor de letra es n
El valor de letra1 es n
El valor de letra2 es n
Eso es
un mensaje
de tres lineas
Me llamo “Jesus”
Me llamo \Jesus\
Variables referenciadas
Asociadas a objetos o instancias de una clase. Se irán estudiando durante el curso.
Casting o transformaciones de tipo
El casting es un procedimiento para transformar una variable primitiva de un tipo a otro, o transformar un objeto de una clase a otra clase siempre y cuando haya una relación de herencia entre ambas (este último casting es el más importante y se verá más adelante).
Dentro del casting de variables primitivas se distinguen dos clases:
- Implícito: no se necesita escribir código para que se lleve a cabo. Ocurre cuando se realiza una conversión ancha (widening casting), es decir, cuando se coloca un valor pequeño en un contenedor grande.
Ejemplo 1:
![]()
Ejemplo 2: similar al anterior.

En cambio,

- Explícito: sí es necesario escribir código. Ocurre cuando se realiza una conversión estrecha (narrowing casting), es decir, cuando se coloca un valor grande en un contenedor pequeño. Son susceptibles de pérdida de datos.
Ejemplo 1:

| NOTA: si se sustituyera la primera línea int num1=100 por int num1=1000000, el código compilaría bien, pero habría pérdida de datos, pues el 1000000 se sale del rango de short [-32768, 32767]. Al mostrar por consola el valor se obtendría un resultado incongruente. |
Ejemplo 2:
![]()
Ejemplo 3: continuación del Ejemplo 2 del casting implícito
Para que la línea
![]()
compile debe hacerse un casting explícito a long
![]()
pero no
![]()
porque, en la línea anterior, 10000000000 es considerado int, mientras que en las de arriba, double.
Dicho esto, se va a analizar un ejemplo un tanto extraño.
- Ejemplo extraño:
![]()
Dado que cualquier entero, por defecto, se almacena en un int (4 bytes), con la línea anterior se pretende colocar un valor grande (el int 10) en un contenedor pequeño (una primitiva de tipo byte con capacidad para 1 byte). Esto, según lo expuesto anteriormente, precisa de casting explícito.
![]()
Pero, resulta que no hace falta, ya que el compilador, cuando se trabaja con enteros, digamos que, provoca un “casting implícito contranatura” y transforma automáticamente a byte el int 10. Ocurriría lo mismo si se trabajara con short y char.
Lo que pasa (y esto es lo que resulta un tanto extraño) es que no ocurre lo anterior con los decimales: por eso, una línea como
![]()
provoca error de compilación. Recordar que cualquier decimal, por defecto, se almacena en un double (8 bytes) y que un tipo float tiene capacidad para 4 bytes. En los decimales, el compilador no fuerza el casting implícito contranatura. De ahí que sea necesario un casting explícito a float para evitar el fallo de compilación.
| NOTA: quizá se evitarían estas situaciones, si el compilador no forzara el casting implícito contranatura a byte, short o char de un int y provocara error de compilación, del mismo modo que cuando se declara un float y no se castea explícitamente. Pero, de momento, esto es lo que hay. |
- Código de partida para explicar el casting entre variables primitivas que almacenan datos numéricos:

Las líneas 3 y 4 almacenan al número 10 mediante una variable primitiva de tipo byte vía “casting implícito contranatura”, el 3000 mediante una de tipo short, también vía “casting implícito contranatura”. Lo más intuitivo es definirlas mediante un casting explícito, pero tal y como están también se puede.
Supuestamente, la línea 5, almacena el 3000000000 mediante una variable de tipo long, vía casting implícito, pero es falso. Ocurre lo que se ha comentado en el Ejemplo 2 del casting implícito: 3000000000 no es considerado como long sino como int y 3000 millones no pertenece al rango asociado a int (aprox. [-2150 millones, 2150 millones]). Si se intenta compilar, se produciría error.
Supuestamente, la línea 6, almacena el 256.5 mediante una variable de tipo float (ocupa 4 bytes en memoria), vía “casting implícito contranatura”, pero, como se ha comentado en el Ejemplo extraño, es falso, ya que en decimales nunca se produce. Debe castearse explícitamente a float.
El código correcto sería:

- Una cuestión a tener en cuenta relacionada con el casting entre variables primitivas es la siguiente:
En Java se realizan automáticamente conversiones de una variable primitiva de un tipo a otra de otro de igual o mayor precisión.
La precisión depende del número de bytes ocupados en memoria y del rango de valores asociado: a mayor número de bytes ocupados, mayor precisión y mayor rango asociado. Así, pasar de byte a short, de short a int, de byte a int, . es automático; en definitiva: pasar de una variable primitiva de un tipo de la cadena de la siguiente línea a otra que se encuentre a su derecha es automático.
byte–>short–>int–>long–>float–>double
Así, por ejemplo, si un método necesita un long como argumento y se le pasa un entero perteneciente al rango de int, promociona automáticamente a long y no es necesario casting.
En cambio, si se le pasa un entero que se sale fuera del rango de int, es necesario realizar un casting para que la llamada al método no provoque error al compilar.
Un ejemplo de esto ocurre con el método estático de java.lang.Thread “void sleep(long retardo)” que introduce un retardo en la ejecución del código, coincidente con el entero, en milisegundos, que se le pasa al argumento. Este método se estudiará más adelante.

Por consola:
Hola
– Después de tres segundos –
Adios
En cambio, si se sustituye
Thread.sleep(3000) por Thread.sleep(3000000000)
no compila ya que el entero que se le pasa no pertenece al rango de int y no puede promocionar a long automáticamente.
Para que compile es necesario hacer un casting explícito:
Thread.sleep(3000000000L)
- Para finalizar con el casting entre primitivas, conviene tener en cuenta lo siguiente:
No es posible realizar casting entre una variable primitiva booleana y cualquier otra variable primitiva.
Sí es posible realizar casting entre una variable primitiva char y una variable primitiva que almacene enteros.
Ejemplo:

Por consola:
ñ
ñ
Los mejores libros para aprender Java
Por Shaddar - java, programacion - 9 Diciembre 2009
Buscando libros de java me he encontrado con una lista con los mejores libros para aprender este lenguaje de programación:
1. Objects First With Java: A Practical Introduction Using BlueJ (2nd Edition)
Autor: Michael Kölling
Descripción:
Start by learning about objects, first; what a great idea! This book begins with the direct manipulation of objects. No public static void main until the 4th chapter.
Autor: Kathy Sierra
Descripción:
Left brain + right brain + humor = comprehension. Written by the founder of Javaranch.com, herself.
3. Java in a Nutshell, Fourth Edition
Autor:
David Flanagan
Descripción:
The only paper reference book you will need.
4. The Java(TM) Developer’s Guide to Eclipse
Autor: Sherry Shavor
Descripción:
You need to learn a powerful IDE, and this is one of the best. The first half deals with learning to use the IDE and the second half shows you how to write plugins for Eclipse.
5. Sun Certified Programmer & Developer for Java 2 Study Guide (Exam 310-035 & 310-027)
Autor: Kathy Sierra
Descripción:
Only if you want to be certifiable! This is a great companion book to Head First Java.
Si los lenguajes de programación fuesen personas
Por Shaddar - humor, programacion - 7 Diciembre 2009
¿Qué pasa si los lenguajes de programación son personas reales como tú y yo? ¿Y si eran parte de las familias y tenía relaciones y los asuntos? ¿Alguna vez has pensado en ir a un supermercado y Visual Basic era la mujer joven que esperaba en la fila delante de usted?
Así lo hicieron los de jeez.eu con su articulo de If Programming Languages Were Real Persons, una traducción aproximada la podeis encontrar aquí.
Charlie C
C is a 70 years old man that knows a lot. Perhaps too proud to reveal what he knows and sometimes too cryptic. He is a very strict person that follows his way of doing things and nothing seems possible to change his mind. In the past he was known as one of the strictest teachers in the Devel City university.
C can make you happy or disappoint you so much that, you want go for one of his sons or daughters. It depends on how much you try to learn his ways. The more you try the more he gives you.
C has been the main builder behind large projects like the Linuxious stadium and other large scaled buildings that we all use. He still works as a freelancer engineer and has involved in many other projects. Even at his age and with a lot of competition mainly from his son C++, C is still the choice of many companies to do things in Devel City.
C has 3 daughters :
- Perl,
- Java and
- C#
and one son, C++.
Vin C++
C++ is 45 years old teacher at the Devel City university, following his father’s steps to become as respected as he is. He loves his father so much that tried to continue his work and knowledge. Being a younger man than C though, made him a much more friendly guy, in the means of approach, than his father. He works as a teacher in the Devel City university and his students have a love and hate affair with him.
C++ often lets his students choose their way in the learning process since he follows a different way of teaching approach than his father used to. His students love him because he lets them work in their own way but sometimes they fear his inheritance of C.
Most of his followers admire his wide range of knowledge that mixes C’s knowledge with knowledge gained through his life.
There are also a lot of people that criticise him of being so wide. Most of the time they talk about him as a direct descendant of C that has adopted all of his fathers disadvantages and added some more to it.
C++ has spent many years to get rid some of his fathers bad habits and never does things not needed. He prefers to put as much effort as needed to do the job right and never bloats things. This is why his projects are much more targeted than his fathers.
Montana Perl
Perl is a 37 years old young woman and works as a data analyst at the department of linguistics in Devel City. As a sexy young woman, her colleagues just love to work with her.
She is extremely clever, very strict when it comes to how people treat to her but has added great value to her carrier with her regular way of expressing things and her unique way of finding needles in haystacks. Many of her colleagues depend on Perl to fix things and they call her a “Swiss knife”.
Her father was a source of inspiration for Perl. Many of her father’s principles was inherited and many more added to her philosophy of how things should be done and why. She is a rather laconic character that speaks less but means a lot.
Perl finds it easy to work on different environments and performs well with a little help from her beloved husband Cygwin who always supports her ambitions.
Perl loves to travel. Each summer she goes around the world, most of the time she will be riding a camel in Africa and many times you might find her playing Golf in the State of the union stadium.
She also loves poetry and runs her own amusement company named Acme which aids in teaching young kids the way to do things the funny way.
Bianca Java
Java is a 35 years old sexy young woman and a mother also. Being so young and mature, Java is one of the most popular women in Devel City. She is very adoptable and can work everywhere. Her name comes as a feature in many projects and a lot of companies want their projects to carry her “Java powered” signature of quality.
Being C++’s sister, does not stop Java to be one of the biggest competitors of her brother. As a woman, Java is clean and manages to keep garbage out of her place, clean and clear. She works at JVM, a company specialized in ports creation.
Java loves sun. Each summer is Java’s favorite season and she loves playing with Duke in the beach.
Java has created her own legacy, just like her father did and has 2 daughters that promise to be as competitive as she is. Her daughters also work at JVM and stand out from the crowd of talented persons in Devel City. Their names are:
- Groovy and
- Scala
Jessica Groovy
Groovy is 21. Young but her impact in Devel City is bigger than just big. She was greatly inspired by her aunt Perl and her best friend Ruby.
Groovy is laconic and very expressive like her aunt, got any possible knowledge of her mother and added some cool ways to do her job in JVM. Most of the time she guides her colleagues in a rather strange way… by adding question marks (?) wherever she thinks something should be checked again.
Jane Scala
Scala is 22 years old.She is sweet and quite friendly but many of her friends in Devel City feel a little thread when it comes to job opportunities. The case of Twittorix, where the managers of the project asked Scala to do the job, made Ruby upset.
Scala like her little sister Groovy, got all of her mother’s knowledge and took it to a newer level. Not only Scala can work the same way as her mother does, she can also make new ways of working and doing things for a specific job which makes her a valuable part of JVM. Scala gets a lot of suggestions to work for NET (another ports creation company) but she is too busy with JVM at the moment that makes this a little hard to accomplish.
Pierson PHP
PHP is 29 years old and Java’s bitter friend. PHP runs her own company in Devel City called Zendix and has become one of the worlds well known ladies because of her easy way of doing things, her adoption of new technologies and a large fun club that make her desirable and efficient.
PHP was a student of C, Java’s father and used to work with Perl where she got her expressive character and power. Being a very beautiful woman, PHP has a lot of admirers that range from newcomers to Devel city, to old residents. She might seem easy but she needs a lot of attention to master her ways.
Sometimes her affairs are too strong and sometimes people seem to glance at Java and Ruby which makes her trying to add some of Java’s charm into her character. This, makes a lot of people say that PHP tries to become Java in some way.
Recently, PHP was voted as the 3rd most popular person in Devel’s city Object’s awards.
Mary JavaScript
JavaScript is often confused with Java in Devel City especially from newcomers… but you know what they say that: “where no smoke without fire”. Many rumors say that JavaScript is Java’s half sister but she denies it, so does Java.
JavaScript is 32 and her close friends call her “JS”. She is very strict but relaxed also. This, makes her a wonderful companion for most of Devel’s residents and she is very popular since a large part of the city has used her services at least once.
JS is one of the most successful women in Devel City. She runs a network of more than 20 companies some of which are unique. jQuerysius, Mootool and Dojodic, to name a few are popping out each and every day.
She works silently and a lot of people think that she spents most of her time to make her job look glamourus. Most of her competitors say that she is good only for that but, to be honest, all of them know that there are some things that only she can accomplish.
She believes that to become successful, you have to keep your friends close and, your enemies closer. So, she tries to cooperate and coexist with all other businessman and businesswoman in Devel City. Everybody loves her even if she breaks things up sometimes.
Angelina Ruby
Ruby is a good friend of Groovy. She is 20 years old and she is one of the upcoming names in Devel City mainly because of her professional maturity and the way she manages to do a job cleanly and fast. Although Scala, Groovy’s sister, got a big job from Ruby’s hands (case of Twittorix), Ruby is still considered as one of the best professionals out there.
Ruby, became one of the most successful women in City of Devel, after the creation of her Rails company and got a lot of fame. She also inspired many other famous women in Devel City to start their own Rails-like companies with PHP being one of them with Symfoniac LTD.
She is a very calm person and not fond of surprises. When she works, she wants to have everything there as helpful as it can be for her and her co-workers. Most of the time she applies the POLS principle to her job.
Some Devel City residents state that, if Perl goes away one day, Ruby will do the job as good as she does and with more freedom than with Perl.
Ruby believes in one principle: “Divide and Conquer”, this is why she has divided all of her company groups into Gems. Ruby just needs to use a gem to do a particular job.
Jack Python
One of the most known and respected persons in Devel City, is Python. A 54 years old construction builder. Some people believe that he can use the power of his brain to do magic. Python works in a rather modern way that his age implies and here is where he amazes Devel’s residents.
Python always finds new ways of doing things. If a tool is good to work with, Python will use it with no particular disadvantages. Python is one of the best man in Devel to work with since he allows anyone to work the way he thinks is better.
His favorite words are spam and eggs and his projects are named after his nickname. For example PyGameing station and PyS6000 which was a futuristic TV series.
Python as his name implies, is a snakes lover and has a lot of them as pets. His favorite pet is an Anaconda.
His work has been approved by some of the biggest companies in Devel City like 10^10, Yohaaa and DERN.
bre indica, es un gran amante de las serpientes. Su mascota preferida es una serpiente de nombre Anaconda.
Visto en | Jeez
Visto en | MundoGeek
Comparación entre algoritmos de ordenación
Por Shaddar - java, programacion - 5 Diciembre 2009

Los algoritmos de ordenación son funciones o métodos que se encargan de ordenar un “array” de datos. Existen varios tipos de métodos de ordenación, pero hoy solo vamos a comentar algunos de los más potentes:
- QuickSort
- MergeSort
- SelectionSort
- BubbleSort
QuickSort
El ordenamiento rápido (quicksort en inglés) es un algoritmo basado en la técnica de “divide y vencerás”, que permite, en promedio, ordenar n elementos en un tiempo proporcional a n log n.
Quizás este sea el algoritmo de ordenación más rápido que existe.
Representación del algoritmo en pseudo-código:
function quicksort(array)
var list less, greater
if length(array) ≤ 1
return array
select and remove a pivot value pivot from array
for each x in array
if x ≤ pivot then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))
Representación del algoritmo en Java:
private static void quickSort(int[] x, int a, int b) {
int i = a, j = b;
int p = x[(a+b)/2];
int v;
do{
while(x[i] < p) i++;
while(x[j] > p) j--;
if( i <= j ){
v = x[j];
x[j] = x[i];
x[i] = v;
i++;
j--;
}
} while (i <= j);
if( a < j ) quickSort(x,a, j);
if( b > i ) quickSort(x,i, b);
}
Representación del algoritmo gráficamente:

MergeSort
El algoritmo de MergeSort se basa en la misma técnica que QuickSort de “divide y vencerás”, y su tiempo de ordenación es proporcional a n log n.
Representación del algoritmo en pseudo-código:
function mergesort(array A[x..y])
begin
if (x-y > 1)):
array A1 := mergesort(A[x..(int( x+y / 2))])
array A2 := mergesort(A[int(1+(x+y / 2))..y])
return merge(A1, A2)
else:
return A
end
function merge(array A1[0..n1], array A2[0..n2])
begin
integer p1 := 0
integer p2 := 0
array R[0..(n1 + n2 + 1)]
while (p1 <= n1 or p2 <= n2):
if (p1 <= n1 and A1[p1] <= A2[p2]):
R[p1 + p2] := A1[p1]
p1 := p1 + 1
if (p2 <= n2 and A1[p1] > A2[p2]):
R[p1 + p2] := A2[p2]
p2 := p2 + 1
return R
end
Representación del algoritmo en Java:
private static void mergeSort( int[ ] x, int[ ] tmpArray, int left, int right ) {
if( left < right ) {
int center = ( left + right ) / 2;
mergeSort( x, tmpArray, left, center );
mergeSort( x, tmpArray, center + 1, right );
merge( x, tmpArray, left, center + 1, right );
}
}
private static void merge( int[ ] x, int[ ] tmpArray, int leftPos, int rightPos, int rightEnd ) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
while( leftPos <= leftEnd && rightPos <= rightEnd )
if( x[ leftPos ] <= x[ rightPos ] )
tmpArray[ tmpPos++ ] = x[ leftPos++ ];
else
tmpArray[ tmpPos++ ] = x[ rightPos++ ];
while( leftPos <= leftEnd )
tmpArray[ tmpPos++ ] = x[ leftPos++ ];
while( rightPos <= rightEnd )
tmpArray[ tmpPos++ ] = x[ rightPos++ ];
for( int i = 0; i < numElements; i++, rightEnd-- )
x[ rightEnd ] = tmpArray[ rightEnd ];
}
Representación del algoritmo gráficamente:

SelectionSort:
El ordenamiento por selección (Selection Sort en inglés) es un algoritmo de ordenamiento que requiere O(n2) operaciones para ordenar una lista de n elementos.
Su funcionamiento es el siguiente:
- Buscar el mínimo elemento de la lísta
- Intercambiarlo con el primero
- Buscar el mínimo en el resto de la lista
- Intercambiarlo con el segundo
Representación del algoritmo en pseudo-código:
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
Representación del algoritmo en Java:
public static void selectionSort(int[] x) {
int n = x.length;
for (int i=0; i<n-1; i++) {
for (int j=i+1; j<n; j++) {
if (x[i] > x[j]) {
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
Representación del algoritmo gráficamente:

BubbleSort
El Ordenamiento 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.
Representación del algoritmo en pseudo-código:
procedure bubbleSort( A : list of sortable items ) defined as:
do
swapped := false
for each i in 0 to length(A) - 2 inclusive do:
if A[i] > A[i+1] then
swap( A[i], A[i+1] )
swapped := true
end if
end for
while swapped
end procedure
Representación del algoritmo en Java:
public static void bubbleSort(int[] x) {
int n = x.length;
for (int pass=1; pass < n; pass++) {
for (int i=0; i < n-pass; i++) {
if (x[i] > x[i+1]) {
int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp;
}
}
}
}
Representación del algoritmo gráficamente:

Comparación de los Algoritmos
Después de explicar los algoritmos, he procedido a cronometrarlos uno a uno ordenando una lista de 10.000 elementos mediante una maquina de Java.
Los resultados fueron los siguientes:
- QuickSort: 1.29 ms de media.
- MergeSort: 1.57 ms de media.
- BubbleSort: 49.08 ms de media.
- SelectionSort: 103.77 ms de media.
Los archivos utilizados para este procedimiento están aquí.
Enlaces | Wikipedia







Últimos Comentarios