sábado, 28 de octubre de 2017

Lógica sucesión de números

Dada la siguiente sucesión de números: 2, 4, 8, 6, 36, 72, 70, 4900, 9800,... mediante el uso de funciones, mostrar en pantalla los términos de esta serie y calcular la suma de N (N se indica por teclado) elementos, es decir, SUMA=2+4+8+6+.....
EXPLICACION DEL PROGRAMA: El programa calcula la suma de la serie anterior para n terminos. Para ello, genera cada uno de los valores de dicha serie hasta el limite ingresado por el usuario. La logica que sigue la serie es de elevar al cuadrado, multiplicar por dos y restar dos.
😐😉












import java.io.*;

public class a9 {
public static void main(String args[])throws IOException {
BufferedReader in; int s=0,a=2;
in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Introduzca el limite N");
int n=Integer.parseInt(in.readLine());
for(int i=0;i<n;) {
 System.out.println(a);
 s=s+a; i++; a=op1(a);
 if(i==n)
break;
 else {
System.out.println(a);
 s=s+a;
a=op2(a); i++;
 }
 if(i==n) break;
else {
System.out.println(a);
 s=s+a;
 a=op3(a); i++; }
 }
 System.out.println("La suma de la serie es: "+s);
}
 public static int op1 (int b) {
return b*b;
}
public static int op2 (int b) {
return b*2;
}
 public static int op3 (int b) {
return b-2;}
}

--------------------Configuration: <Default>--------------------
Introduzca el limite N
4
2
4
8
6
La suma de la serie es: 20

Process completed.

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.