Sorting: Bubble Sort

Sort by

recency

|

402 Discussions

|

  • + 0 comments

    Having a question where the formatting of the answer needs to be exact is misleading. I had an extra space

    Compiler Message

    Wrong Answer

    Input (stdin)

    3
    
    1 2 3
    

    Your Output (stdout)

    Array is sorted in 0 swaps.
    
    First Element:  1
    
    Last Element:  3
    

    Expected Output

    Array is sorted in 0 swaps.
    
    First Element: 1
    
    Last Element: 3
    
  • + 0 comments
    def countSwaps(a):
        temp = 0
        count = 0
        i = 0
       
        while i < len(a):
            idx = 0
            while idx < len(a)-1:
                    if a[idx] > a[idx+1]:
                        count = count + 1
                        temp = a[idx]
                        a[idx] = a[idx+1]
                        a[idx+1] = temp
                    idx = idx + 1
            i = i + 1
              
    
        
        print("Array is sorted in " + str(count) + " swaps.") 
        print("First Element:", a[0])
        print("Last Element:", a[len(a)-1])
    
  • + 0 comments

    Python:

        s = 0
        for i in range(1, len(a)):
            for j in range(i):
                if a[j] > a[i]:
                    s += 1
                    a[i], a[j] = a[j], a[i]
    
  • + 0 comments

    Java:

     public static void countSwaps(List<Integer> a) {
    // Write your code here
        int count = 0;
        int n = a.size();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                if (a.get(j) > a.get(j+1)) {
                    count += 1;
                    Collections.swap(a, j, j+1);
                }
            }
    
        }
        System.out.println("Array is sorted in "+ count+ " swaps.");
        System.out.println("First Element: " + a.get(0));
        System.out.println("Last Element: " + a.get(n-1));
    }
    
  • + 0 comments

    javascript

    function countSwaps(a) {
      let count = 0
      for(let i=0; i<a.length; i++) {
        for(let j=0; j<a.length-1; j++) {
          if(a[j]>a[j+1]) {
            swap(a,j,j+1)
            count ++
          }
        }
      }
      
      console.log("Array is sorted in", count, "swaps.")
      console.log("First Element:", a[0])
      console.log("Last Element:", a[a.length - 1])
    }
      
    function swap(arr, i1, i2){
      let temp = arr[i1]
      arr[i1] = arr[i2]
      arr[i2] = temp
    }