# Sorting: Bubble Sort

# Sorting: Bubble Sort

thugwaffle + 0 comments I think this is a bit too easy to classify as "Medium", especially since you not only give most of the code in the question, but the solution too!

amrkhaledccd + 0 comments This should be classified as easy. The fact it is marked as Medium made me think 100 times before submitting my solution, i thought there is something i didn't understand

MaxNRG + 0 comments Python 3 solution:

n = int(input().strip()) a = list(map(int, input().strip().split(' '))) numSwaps = 0 while True: SwapsFlag = False for i in range(len(a)-1): if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] numSwaps += 1 SwapsFlag = True if not SwapsFlag: break print('Array is sorted in', numSwaps, 'swaps.') print('First Element:', a[0]) print('Last Element:', a[-1])

X1011 + 0 comments fun fact: you don't need to actually perform the bubble sort to find the total number of swaps necessary; you can just count the inversions, as in the problem Merge Sort: Counting Inversions. not that it would be easier to code, but it would have lower time complexity.

khuatgia + 0 comments Hi everyone. I keep getting wrong answers even though my outputs are exactly the same as expected output. Does anyone has the same issue ? Here is my solution:

static void countSwaps(int[] a) {

`int n = a.length; int counter = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; counter++; } } } System.out.println("Array is sorted in " + counter + " swaps."); System.out.println("First element: " + a[0]); System.out.println("Last element: " + a[n - 1]); return; }`

Sort 247 Discussions, By:

Please Login in order to post a comment