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 class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> a = Stream.of(bufferedReader.readLine().trim().split("\\s+"))
.map(Integer::parseInt)
.collect(Collectors.toList());
int totalSwaps = 0;
for (int i = n - 1; i > 0; i--) {
int swapsInPass = 0;
for (int j = 0; j < i; j++) {
if (a.get(j) > a.get(j + 1)) {
Collections.swap(a, j, j + 1);
swapsInPass++;
totalSwaps++;
}
}
if (swapsInPass == 0) break; // Stop early if no swaps in this pass
}
System.out.println("Array is sorted in " + totalSwaps + " swaps.");
System.out.println("First Element: " + a.get(0));
System.out.println("Last Element: " + a.get(n - 1));
bufferedReader.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 20: Sorting
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.; import java.util.stream.*;
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}