Sorting: Bubble Sort

Sort by

recency

|

401 Discussions

|

  • + 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
    }
    
  • + 0 comments

    JAVA 8

    public static void countSwaps(List<Integer> a) {
            int count = 0;
            for (int i = 0; i < a.size(); i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (a.get(j) > a.get(j + 1)) {
                        int aux = a.get(j);
                        a.set(j, a.get(j + 1));
                        a.set(j + 1, aux);
                        count++;
                    }
                }
            }
            System.out.println("Array is sorted in " + count + " swaps.");
            System.out.println("First Element: " + a.get(0));
            System.out.println("Last Element: " + a.get(a.size() - 1));
        }