Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.lang3.ArrayUtils;
- public class Insertion {
- static void print(Comparable[] a) {
- for (Comparable i : a) System.out.print(i + " ");
- System.out.println();
- }
- static void swap(Comparable [] a, int p, int q) {
- Comparable temp = a[p];
- a[p] = a[q];
- a[q] = temp;
- }
- static boolean less(Comparable a, Comparable b) {
- return a.compareTo(b) < 0;
- }
- public static boolean isSorted(Comparable[] a) {
- for (int i = 1; i < a.length; i++) {
- if (less(a[i], a[i - 1])) return false;
- }
- return true;
- }
- public static void sort(Comparable[] a) {
- for (int i = 1; i < a.length; i++) {
- for (int j = i; j > 0; j--) {
- if (a[j].compareTo(a[j - 1]) < 0){
- swap(a, j, j - 1);
- print(a);
- }
- else break;
- }
- }
- }
- public static void main(String[] args) {
- String s = "SHELLSORTEXAMPLE";
- Character[] a= ArrayUtils.toObject(s.toCharArray());
- // Integer[] a = new Integer[]{31, 41, 59, 26, 41, 58};
- print(a);
- sort(a);
- if (!isSorted(a)) throw new AssertionError("Array not sorted");
- print(a);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement