Error in sorting by selection in java

0

I'm doing an exercise with sort ordering algorithm ascending, however when I execute it orders only the index 0 of the vector and I repeat this same value for the index 1 of the vector, and the other value is lost, the I have actually looked at several sites comparing my code with others and I do not see any error. Here I leave the code to see if you can see what error I'm committing.

package VariablesyCondicionales;

import java.io.PrintWriter;
import java.util.Random;

public class OrdenamientoSeleccion {

    public static void main(String[] args) {

        Random r = new Random();
        PrintWriter p = new PrintWriter(System.out,true);

        int ind_menor;

        int v1[] = {9,5};
        /*int v1[] = new int[2];

        v1[0]= r.nextInt(100);
        v1[1]= r.nextInt(100);*/


        p.println("Vector orignal\n");

        for(int i=0;i<v1.length;i++) {
            p.println("V"+i+"["+v1[i]+"]");
        }

        p.println("Vector organizado de manera ascendente con el metodo de Seleccion");

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

            ind_menor=v1[i];
            for(int j=i+1;j<v1.length;j++) {
                if(v1[j]<ind_menor) {
                    ind_menor=v1[j];
                }               
            }
            if(v1[i] != ind_menor) {
                int aux = v1[i];
                v1[i] = ind_menor;
                ind_menor = aux ;
            }
        }

        for(int i=0;i<v1.length;i++) {
            p.println("V"+i+"["+v1[i]+"]");

        }
    }

}
    
asked by Andres G. 22.11.2017 в 17:45
source

2 answers

2

In your variable ind_menor you must save the index of the element, not the element as such:

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

        p.println("iteracion: " + i);

        ind_menor=i;
        for(int j=i+1;j<v1.length;j++) {
            if(v1[j]<v1[ind_menor]) {
                ind_menor=j;
            }               
        }
        if(v1[i] != v1[ind_menor]) {
            int aux = v1[i];
            v1[i] = v1[ind_menor];
            v1[ind_menor] = aux ;
        }
    }
    
answered by 22.11.2017 в 18:14
-1

Check that the selection should be about the index and not about the value of the vector in the index, that is, ind_menor=i instead of ind_menor=v1[i] , following this rule your code would look like this:

for(int i=0;i<=v1.length-1;i++) {    
    ind_menor=i;
    for(int j=i+1;j<v1.length;j++) {
        if(v1[j]<v1[ind_menor]) {
            ind_menor=i;
        }               
    }
    if(i != ind_menor) {
        int aux = v1[i];
        v1[i] = v1[ind_menor];
        v1[ind_menor] = aux ;
    }
}
    
answered by 22.11.2017 в 18:16