Search code examples
javamethodsbubble-sort

Bubble Sort Method + Permutation Method Inside


I would need some help for this exercise. I have to create a method containing bubble sort and inside this method another one that swap values. I tried this :

public static void main(String[] args) {

        int i, taille = 5;
        int[] tableau = new int [taille];

        Scanner readKeyboard = new Scanner(System.in);

        System.out.println("Introduisez des valeurs positives ou négatives");

        for (i=0; i < taille; i++)
        {
            tableau[i] = readKeyboard.nextInt();
        }

        bubblesort(tableau);

        System.out.println("Tableau trié");

        for (i=0; i < taille; i++)
        {
            System.out.println(tableau[i]);
        }

    }

    public static void swapping(int a, int b)
    {
        int tmp;

        tmp     =   a;
        a       =   b;
        b       =   tmp;

    }

    public static void bubblesort(int[] tab)   
    {  
        int i, j;
        for(i=0; i < tab.length; i++) 
        {
                for(j=1; j < (tab.length-i); j++)
                {  
                        if(tab[j-1] > tab[j])
                        {
                            swapping(tab[j-1], tab[j]);
                        }
                }
        }
    }

And my problem is that my values aren't swapped inside the bubble sort method. Should I have used another type of method than void for them or just for the swapping ?


Solution

  • You need to update your "swapping" method with the following one.

     private static void swapping(int[] array,int i,int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }