lauraloperfido / Java

Codice Java
0 stars 0 forks source link

Selection Sort #2

Open lauraloperfido opened 7 years ago

lauraloperfido commented 7 years ago

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    new Main().run();
}

public void run(){
    System.out.println("Inserisci numero elementi");
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    System.out.println("Hai inserito " + n + " elementi");

    int[] v = new int[n];
    for(int i=0; i<n; i++)
    {   System.out.println("Inserisci valori");
        v[i]=scan.nextInt();
        //per assegnare al vettore il valore, basta richiamare Scanner tramite Scan
    }
    System.out.println("Il vettore è");
    System.out.print("[ ");
    for (int i = 0; i < n; i++)
        System.out.print(v[i] +  " ");
    System.out.print("]");
    System.out.print("");

    SelectionSort(v, n);

    // Stampo il vettore dopo l'ordinamento
    System.out.println("Il tuo vettore ordinato è");
    System.out.print("[ ");
    for(int i = 0; i < n; i++){
        System.out.print(v[i] + " ");
            }
    System.out.print("]");
}

public void SelectionSort(int[] v, int dim) {
    int i = 0;
    int j = 0;
    int k = 0;

    for (i = 0; i < dim -1; i++) {
        k = i;
        for (j = i+1; j < dim; j++ ) {
            if (v[j] < v[k])
                k = j;
        }

        scambia_componenti(v, i, k);
    }
}

public void scambia_componenti(int[] v, int c1, int c2) {
    int temp = v[c1];
    v[c1] = v[c2];
    v[c2] = temp;
}

}

FabianaOsnato commented 7 years ago

interessante