organize an array recursively in java

Technology

organize an array recursively in java

how to organize an array recursively in java with tutorial data structure

organize an array recursively in java
img organize an array recursively in java



There are many ways to organize an array in java, such as the bubble method which orders it step by step through the array or vector dynamically but that we need to go through it recursively and calling ourselves in this post we will go through the vector recursively and dynamically.

To organize from least to greatest we will create a class called Recursividad as in the following image:
organize an array recursively in java tutorial1

In that class we will place the following code:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html
 * and open the template in the editor.
 */
package recursividad;

import java.util.Arrays;
/**
 *
 * @author https://www.mbajava.com/
 */
public class Recursividad {
    public static int[] array = {6, 3, 5, 9, 4};
    public static void ordenar(int posicion) {
        if (posicion > 1) {
            ordenar(posicion - 1);
        }
        int x = posicion - 1;
        int numero = array[x];
        while ((x > 0) && (array[x - 1] > numero)) {
            array[x] = array[x - 1];
            x--;
        }
        array[x] = numero;
    }
}

Here we travel recursively and send a position to know where in the vector we stand to organize them recursively and finally we call the main function to call the function sort and print on screen:

/**
     * @param args https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html

     */
    public static void main(String[] args) {
        // TODO code application logic here
        ordenar(array.length);
        System.out.println("array ordenado:" + Arrays.toString(array));

    }

when executing it we see what it is called to order the array from least to greatest and complete code here:

import java.util.Arrays;
/**
 *
 * @author https://www.mbajava.com/
 */
public class Recursividad {
    public static int[] array = {6, 3, 5, 9, 4};
    public static void ordenar(int posicion) {
        if (posicion > 1) {
            ordenar(posicion - 1);
        }
        int x = posicion - 1;
        int numero = array[x];
        while ((x > 0) && (array[x - 1] > numero)) {
            array[x] = array[x - 1];
            x--;
        }
        array[x] = numero;
    }
    /**
     * @param args https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html

     */
    public static void main(String[] args) {
        // TODO code application logic here
        ordenar(array.length);
        System.out.println("array ordenado:" + Arrays.toString(array));

    }

}

Post a Comment

0 Comments