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.
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));
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sorting: Bubble Sort
You are viewing a single comment's thread. Return to all comments →
Java: