miércoles, 9 de noviembre de 2016

Merge sort

Merge sort

public class MergeSort { 

private int[] array; 
private int[] tempMergArr; 
private int length; 

public static void main(String a[]) { 

int[] inputArr = { 32, 27, 51, 89, 1, 98, 9, 28, 65, 0 }; 
MergeSort mms = new MergeSort(); 
mms.sort(inputArr); 

for (int i : inputArr) { 

System.out.print(i); 
System.out.print(" "); 




public void sort(int inputArr[]) { 

this.array = inputArr; 
this.length = inputArr.length; 
this.tempMergArr = new int[length]; 
doMergeSort(0, length - 1); 



private void doMergeSort(int lowerIndex, int higherIndex) { 

if (lowerIndex < higherIndex) { 

int middle = lowerIndex + (higherIndex - lowerIndex) / 2; 
// Below step sorts the left side of the array 
doMergeSort(lowerIndex, middle); 
// Below step sorts the right side of the array 
doMergeSort(middle + 1, higherIndex); 
// Now merge both sides 
mergeParts(lowerIndex, middle, higherIndex); 




private void mergeParts(int lowerIndex, int middle, int higherIndex) { 

for (int i = lowerIndex; i <= higherIndex; i++) { 

tempMergArr[i] = array[i]; 



int i = lowerIndex; 
int j = middle + 1; 
int k = lowerIndex; 

while (i <= middle && j <= higherIndex) { 

if (tempMergArr[i] <= tempMergArr[j]) { 

array[k] = tempMergArr[i]; 
i++; 

} else { 

array[k] = tempMergArr[j]; 
j++; 



k++; 


while (i <= middle) { 

array[k] = tempMergArr[i]; 
k++; 
i++; 




}










--------------------Configuration: <Default>--------------------
0 1 9 27 28 32 51 65 89 98 

Process completed.

martes, 8 de noviembre de 2016

Shell Sort

Method Shell Sort

public class ShellSort {

private long[] data;
private int len;

public ShellSort(int max) {

data = new long[max];
len = 0;

}

public void insert(long value) {

data[len] = value;
len++;

}

public void display() {

for (int j = 0; j < len; j++) {

System.out.print(data[j] + " ");

}

System.out.println("");
}

public void shellSort() {

int inner, outer;
long temp;
// find initial value of h

int h = 1;

while (h <= len / 3) {

h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
}

while (h > 0) // decreasing h, until h=1
{
// h-sort the file
for (outer = h; outer < len; outer++) {

temp = data[outer];
inner = outer;

// one subpass (eg 0, 4, 8)
while (inner > h - 1 && data[inner - h] >= temp) {

data[inner] = data[inner - h];
inner -= h;

}

data[inner] = temp;
}

h = (h - 1) / 3; // decrease h
}
}

public static void main(String[] args) {

int maxSize = 10;
ShellSort arr = new ShellSort(maxSize);

for (int j = 0; j < maxSize; j++) {

long n = (int) (java.lang.Math.random() * 99);
arr.insert(n);

}

System.out.print("Unsorted List:\n");
arr.display();

arr.shellSort();

System.out.print("-------------------------\n");
System.out.print("Sorted List:\n");
arr.display();
}
}








--------------------Configuration: <Default>--------------------
Unsorted List:
30 8 86 63 89 38 71 94 79 64 
-------------------------
Sorted List:
8 30 38 63 64 71 79 86 89 94 

Process completed.

lunes, 7 de noviembre de 2016

Method Heap Sort (Método de ordenamiento Heap Sort)

Método de ordenamiento Heap Sort








public class HeapSort { 

public static void main(String a[]) { 

int i; 
int arr[] = { 1, 3, 4, 5, 2 }; 

System.out.println("\nHeap Sort\n---------------"); 
System.out.println("\nUnsorted Array\n---------------"); 

for (i = 0; i < arr.length; i++){ 

System.out.print(" " + arr[i]); 



for (i = arr.length; i > 1; i--) { 

fnSortHeap(arr, i - 1); 



System.out.println("\n\nSorted array\n---------------"); 

for (i = 0; i < arr.length; i++){ 

System.out.print(" " + arr[i]); 





public static void fnSortHeap(int array[], int arr_ubound) { 

int i, o; 
int lChild, rChild, mChild, root, temp; 

root = (arr_ubound - 1) / 2; 

for (o = root; o >= 0; o--) { 

for (i = root; i >= 0; i--) { 

lChild = (2 * i) + 1; 
rChild = (2 * i) + 2; 

if ((lChild <= arr_ubound) && (rChild <= arr_ubound)) { 

if (array[rChild] >= array[lChild]) 
mChild = rChild; 
else 
mChild = lChild; 

} else { 

if (rChild > arr_ubound) 
mChild = lChild; 
else 
mChild = rChild; 



if (array[i] < array[mChild]) { 

temp = array[i]; 
array[i] = array[mChild]; 
array[mChild] = temp; 





temp = array[0]; 
array[0] = array[arr_ubound]; 
array[arr_ubound] = temp; 
return; 


}

--------------------Configuration: <Default>--------------------

Heap Sort
---------------

Unsorted Array
---------------
 1 3 4 5 2

Sorted array
---------------
 1 2 3 4 5

Process completed.

domingo, 6 de noviembre de 2016

Method Quick Sort

Method Quick Sort

Selection sort





public class QuickSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println("Quick Sort\n\n");
System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++) {

System.out.print(array[i] + "  ");

}

System.out.println();

quick_srt(array, 0, array.length - 1);

System.out.print("\nValues after the sort:\n\n");

for (i = 0; i < array.length; i++) {

System.out.print(array[i] + "  ");

}

System.out.println();
}

public static void quick_srt(int array[], int low, int n) {

int lo = low;
int hi = n;

if (lo >= n) {

return;

}

int mid = array[(lo + hi) / 2];

while (lo < hi) {

while (lo < hi && array[lo] < mid) {

lo++;

}

while (lo < hi && array[hi] > mid) {

hi--;

}

if (lo < hi) {

int T = array[lo];
array[lo] = array[hi];
array[hi] = T;

}
}

if (hi < lo) {

int T = hi;
hi = lo;
lo = T;

}

quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);

}
}

--------------------Configuration: <Default>--------------------
Quick Sort


Values Before the sort:

12  9  4  99  120  1  3  10  13

Values after the sort:

1  3  4  9  10  12  13  99  120

Process completed.

sábado, 5 de noviembre de 2016

Ejemplo de método e ordenamiento por seleccion (Selection sort)


Selection sort





public class SelectionSortExample { 

public static int[] doSelectionSort(int[] arr) { 

for (int i = 0; i < arr.length - 1; i++) { 

int index = i; 

for (int j = i + 1; j < arr.length; j++) { 

if (arr[j] < arr[index]) { 

index = j; 



int smallerNumber = arr[index]; 
arr[index] = arr[i]; 
arr[i] = smallerNumber; 


return arr; 

public static void main(String a[]) { 

int[] arr1 = { 102, 34, 2, 56, 76, 5, 88, 42 }; 
int[] arr2 = doSelectionSort(arr1); 

for (int i : arr2) { 

System.out.print(i); 
System.out.print(", "); 


}

--------------------Configuration: <Default>--------------------
2, 5, 34, 42, 56, 76, 88, 102, 
Process completed.

viernes, 4 de noviembre de 2016

Metodo de ordenamiento Insertion sort

Insertion sort





public class InsertionSortExample {

static int step = 1;

    public static void main(String[] args) {
       
        int[] input = { 7, 21, 91, 43, 23, 17, 34, 9, 1 };
        insertionSort(input);
    }
   
    private static void printNumbers(int[] input) {
       
    System.out.println("Step "+step);
    System.out.println("-----------------------------");
    step++;
 
        for (int i = 0; i < input.length; i++) {
     
            System.out.print(input[i] + ", ");
         
        }
     
        System.out.println("\n");
    }

    public static void insertionSort(int array[]) {
 
        int n = array.length;
     
        for (int j = 1; j < n; j++) {
     
            int key = array[j];
            int i = j-1;
         
            while ( (i > -1) && ( array [i] > key ) ) {
         
                array [i+1] = array [i];
                i--;
             
            }
         
            array[i+1] = key;
            printNumbers(array);
        }
    }
}


--------------------Configuration: <Default>--------------------
Step 1
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,

Step 2
-----------------------------
7, 21, 91, 43, 23, 17, 34, 9, 1,

Step 3
-----------------------------
7, 21, 43, 91, 23, 17, 34, 9, 1,

Step 4
-----------------------------
7, 21, 23, 43, 91, 17, 34, 9, 1,

Step 5
-----------------------------
7, 17, 21, 23, 43, 91, 34, 9, 1,

Step 6
-----------------------------
7, 17, 21, 23, 34, 43, 91, 9, 1,

Step 7
-----------------------------
7, 9, 17, 21, 23, 34, 43, 91, 1,

Step 8
-----------------------------
1, 7, 9, 17, 21, 23, 34, 43, 91,


Process completed.

martes, 1 de noviembre de 2016

Método de ordenamiento por intercambio (Exchange sort)

Exchange sort


Si alguien te hace volar, asegúrate de caer de pie cuando te suelte… ¡porque te soltará!








import java.util.*;
public class ExchangeSort
{
    public static void main(String[] args)
    {
        int[] array;
        int i, j, temp, size;

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the size of array");//Introduzca el tamaño de la matriz
        size = sc.nextInt();
        array = new int[size];

        System.out.println("Enter the elements of array : "); //Introduzca los elementos de la matriz
        for (i = 0; i < size; i++)
        {

            array[i] = sc.nextInt();
        }

        //Exchange sort , ordenacion de intercambio
        for (i = 0; i < (size - 1); i++)
        {
            for (j = (i + 1); j < size; j++)
            {
                if (array[i] > array[j])
                {
                    temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }

        System.out.println("Sorted Array is : "); //el vector ordenado es
        for (i = 0; i < size; i++)
        {
            System.out.print(array[i] + " ");
        }
    }
}

--------------------Configuration: <Default>--------------------
Enter the size of array
3
Enter the elements of array : 
2
5
7
Sorted Array is : 
2 5 7 
Process completed.

lunes, 31 de octubre de 2016

Enumeration sort

EnumerationSort
El éxito de la vida no está en vencer siempre, sino en no darse por vencido nunca. 





import java.util.*;

public class EnumerationSort {

    public static void main(String[] args) {

        //// Crea datos aleatorios para ordenar la fuente. Utilizará java.util.Vector
         // Para almacenar el número entero aleatorio generado.
        // Creates random data for sorting source. Will use java.util.Vector
        // to store the random integer generated.
        //

        Random random = new Random();
        Vector<Integer> data = new Vector<Integer>();

        for (int i = 0; i < 10; i++) {

            data.add(Math.abs(random.nextInt()));

        }

        //Obtener la enumeración del objeto vectorial y convertirlo en
         // Un java.util.List. Por último, ordenar la lista utilizando Collections.sort()
        // Get the enumeration from the vector object and convert it into
        // a java.util.List. Finally we sort the list using
        // Collections.sort() method.
        //

        Enumeration enumeration = data.elements();
        List<Integer> list = Collections.list(enumeration);
        Collections.sort(list);

        //
        // Prints out all generated number after sorted.
        //

        for (Integer number : list) {

            System.out.println("number = " + number);

        }
    }
}
--------------------Configuration: <Default>--------------------
number = 36553190
number = 469661102
number = 488613848
number = 646902854
number = 732394063
number = 814608861
number = 880474004
number = 916061347
number = 1062354281
number = 1082061349

Process completed.

The success of life is not always win, but not give up ever.

viernes, 28 de octubre de 2016

Método de ordenamiento de burbuja (bubble sort)






BUBBLE SHORT 

THE BEST WAY TO LEARN IS THE PRACTICE (LA MEJOR FORMA DE APRENDER ES LA PRACTICA)

import java.util.Scanner;

class BubbleSort {

  public static void main(String []args) {

    int n, c, d, swap; //swap para intercambiar
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");//introducir numeros enteros a  ordenar
    n = in.nextInt();

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    for (c = 0; c < ( n - 1 ); c++) {
      for (d = 0; d < n - c - 1; d++) {
        if (array[d] > array[d+1]) /* For descending order use < */
        {
          swap       = array[d];
          array[d]   = array[d+1];
          array[d+1] = swap;
        }
      }
    }

    System.out.println("Sorted list of numbers");// lista ordenada de numeros

    for (c = 0; c < n; c++)
      System.out.println(array[c]);
  }
}

--------------------Configuration: <Default>--------------------
Input number of integers to sort
10
Enter 10 integers
13
24
34
56
77
55
654
67
45
87
Sorted list of numbers
13
24
34
45
55
56
67
77
87
654

Process completed.

miércoles, 29 de junio de 2016

Como crear un JDialog en java usando jcreator


Para crear un cuadro de dialogo en java como el siguiente necesitamos hacer 2 archivos java uno llamado VentanaDialogoError.java  y otro llamado ejem.java este sera la clase principal con el método Main (Principal) bueno a continuación les dejo los códigos del ejemplo, pueden cambiar el texto del mensaje y poner lo que gusten. 







import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class VentanaDialogoError implements ActionListener{

    private JDialog dialogo;
    private JButton boton;

    public  void creaDialogoError(String titulo, String contenido){

        dialogo = new JDialog();
        dialogo.setTitle(titulo);
        dialogo.setModal(true);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2,1,3,3));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel texto = new JLabel(contenido);
        panel.add(texto);

        boton = new JButton("Aceptar");
        boton.addActionListener(this);
        panel.add(boton);

        dialogo.setContentPane(panel);
        dialogo.pack();
        dialogo.setResizable(false);
        dialogo.setLocationRelativeTo(null);
        dialogo.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){

        if(e.getActionCommand().equals("Aceptar")){
            dialogo.dispose();
        }

    }
}

public class ejem {      
   
   public static void main (String [] args) {
    VentanaDialogoError vDialogoError=new VentanaDialogoError();

    vDialogoError.creaDialogoError("ERROR", "Ejemplo de mensaje de error ");
    }
}

viernes, 6 de mayo de 2016

Calcular longitud de circunferencia, y elevar x numero al cuadrado

import java.util.Scanner;

public class Calcular {

    public static void main(String[] args) {  
           Scanner leer = new Scanner(System.in);
           double radio;
           int n;      
           
           System.out.print("Introduzca el radio de la circunferencia: ");
           radio = leer.nextDouble();
           System.out.println("Longitud de la circunferencia: " + 2*Math.PI*radio);
         
           System.out.print("Introduzca un número entero: ");
           n = leer.nextInt();
           System.out.println("El cuadrado es: " + Math.pow(n,2));
     }
}

--------------------Configuration: <Default>--------------------
Introduzca el radio de la circunferencia: 5
Longitud de la circunferencia: 31.41592653589793
Introduzca un número entero: 5
El cuadrado es: 25.0

Process completed.

domingo, 10 de abril de 2016

Hacer un programa que calcule la suma de los números pares e impares que se encuentran entre 10 y 30. El programa deberá calcular lo siguiente: o El total de números pares. o La suma de los números pares. o El total de números impares. o La suma de los números impares. o La suma total de todos los números.






Hacer un programa que calcule la suma de los números pares e impares que se encuentran entre 10 y 30. El programa deberá calcular lo siguiente:
o El total de números pares.
o La suma de los números pares.
o El total de números impares.
o La suma de los números impares.
o La suma total de todos los números.

import java.util.*;
public class ejemplo {
public static void main (String[] args)
    {
        Scanner teclado= new Scanner(System.in);

        int i, s=0,ss=0,total=0, c=0, cc=0, vec[];
        String a;
        for(i=10;i<=30;++i)
        {
            System.out.print(" \n Numero del 10 al 30  "+i+": ");
     total=total+i;
         
            if(i%2==0){
            System.out.print("Numero Par "+i+": ");
            c++;
        s=s+i;
         
            }
           
            else {
            System.out.print("Numero impar "+i+": ");
           ss=ss+i;
         
             cc++;
           }
            }
           System.out.print("\nTotal Numero Par "+ c);
            System.out.print("\nTotal Numero imPar "+ c);
             System.out.print("\nsuma Total Numero Par "+ s);
             System.out.print("\nsuma Total Numero imPar "+ ss);
              System.out.print("\nsuma Total Numeros del 10 al 30 : "+ total);
        }
          }
       
     

--------------------Configuration: <Default>--------------------

 Numero del 10 al 30  10: Numero Par 10:
 Numero del 10 al 30  11: Numero impar 11:
 Numero del 10 al 30  12: Numero Par 12:
 Numero del 10 al 30  13: Numero impar 13:
 Numero del 10 al 30  14: Numero Par 14:
 Numero del 10 al 30  15: Numero impar 15:
 Numero del 10 al 30  16: Numero Par 16:
 Numero del 10 al 30  17: Numero impar 17:
 Numero del 10 al 30  18: Numero Par 18:
 Numero del 10 al 30  19: Numero impar 19:
 Numero del 10 al 30  20: Numero Par 20:
 Numero del 10 al 30  21: Numero impar 21:
 Numero del 10 al 30  22: Numero Par 22:
 Numero del 10 al 30  23: Numero impar 23:
 Numero del 10 al 30  24: Numero Par 24:
 Numero del 10 al 30  25: Numero impar 25:
 Numero del 10 al 30  26: Numero Par 26:
 Numero del 10 al 30  27: Numero impar 27:
 Numero del 10 al 30  28: Numero Par 28:
 Numero del 10 al 30  29: Numero impar 29:
 Numero del 10 al 30  30: Numero Par 30:
Total Numero Par 11
Total Numero imPar 11
suma Total Numero Par 220
suma Total Numero imPar 200
suma Total Numeros del 10 al 30 : 420
Process completed.