Search code examples
pythonsortingbubble-sort

Why is my BubbleSort algorithm working in Java but not in Python


Why does this code seem to work:

package de.Algos;

import java.util.Arrays;

public class Sort {
    public static int[] swap(int[] A, int i, int j) {
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        return A;
    }

    public static int[] bubbleSort(int[] A){
        int n = A.length;
        for(int i=0;i<=n-2;i++){
            for(int j=0;j<=n-2-i;j++){
                if(A[j]>A[j+1]){
                    swap(A,j,j+1);
                }
            }
        }
        return A;
    }

    public static void main(String[] args){
        int[] A = {12,3,4,5,24,5,3,35352,24,13513513,33};
        System.out.println(Arrays.toString(A));
        A = bubbleSort(A);
        System.out.println(Arrays.toString(A));
    }
}

Java Output

While my translation to Python doesn't:

# currently not working yet

def swap(A, a, b): 
    A[a], A[b] = A[b], A[b]
    return A

def bubbleSort(A, n):
    for i in range(0,n-1,1):
        for j in range(0,n-1-i,1):
            if A[j] > A[j+1]:
                A = swap(A,j,j+1)
                display(f'Swapped {A[j]} at {j} with {A[j+1]} at {j+1}')
    return A   
A = [0, 1, 4, 25, 5, 745, 253264, 3]
display(A)
A = bubbleSort(A, len(A))
display(A)

Python Output

Which stupid mistake did I make?

I really can't find it. Maybe it is in the for functions in Python via range behaving differently? Is there any more elegant solution you can make up to make it look as close to the pseudocode given?

BubbleSort(A, n)
for i←0 to n-2 {
 for j←0 to n-2-i {
 if (A[j] > A[j+1]) {
     swap(A, j, j+1)
 }
 }
}

Kind regards and thanks,


Solution

  • I can see that your swap method definition in python is not the same as in Java.

    In Java you're indeed swapping the A[j] and A[j+1]. In Python, there's no swap as A[j] = A[j+1] but A[j+1] remains the same. Try:

    def swap(A, a, b): 
        A[a], A[b] = A[b], A[a]
        return A