Skip to content

Instantly share code, notes, and snippets.

@AlinaWithAFace
Created April 21, 2018 01:07
Show Gist options
  • Save AlinaWithAFace/03fe27cc0930b73043736c14d86eb93c to your computer and use it in GitHub Desktop.
Save AlinaWithAFace/03fe27cc0930b73043736c14d86eb93c to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
// Write Your Code Here
int totalSwaps = 0;
for (int i = 0; i < n; i++) {
// Track number of elements swapped during a single array traversal
int numberOfSwaps = 0;
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
//swap(a[j], a[j + 1]);
numberOfSwaps++;
totalSwaps++;
}
}
// If no elements were swapped during a traversal, array is sorted
if (numberOfSwaps == 0) {
break;
}
}
System.out.printf("Array is sorted in %d swaps.\n", totalSwaps);
System.out.printf("First Element: %d\n", a[0]);
System.out.printf("Last Element: %d", a[n - 1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment