We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

- Sorting: Bubble Sort
- Discussions

# Sorting: Bubble Sort

# Sorting: Bubble Sort

+ 5 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!

+ 1 comment 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

+ 2 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.

+ 7 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])

+ 2 comments **JAVA 8**BubbleSort Solution:static void countSwaps(int[] a) { int count = 0; boolean flag = false; while (!flag) { flag = true; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; flag = false; count++; } } } System.out.println(String.format( "Array is sorted in %d swaps.%n" + "First Element: %d%n" + "Last Element: %d%n", count, a[0], a[a.length - 1])); }

Load more conversations

Sort 351 Discussions, By:

Please Login in order to post a comment