Sorting: Bubble Sort

Sort by

recency

|

403 Discussions

|

  • + 0 comments
    def countSwaps(a):
        count = 0
        n = len(a)-1
        for passes in range(n):
            for i in range(n-passes):
                if a[i]>a[i+1]:
                    a[i],a[i+1]=a[i+1],a[i]
                    count+=1
        # print(a,passes-1)
        print(f"Array is sorted in {count} swaps.\nFirst Element: {a[0]}\nLast Element: {a[-1]}")
    
  • + 1 comment

    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

      I found your porblem! your output:

      Last Element:  3
      

      Here you made a mistake, there are two white spaces before 1 and 3. Remove one space in your formated code part. Happy Coding!

  • + 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));
    }