Advertisement
tejasomina

Insertion.java

Oct 21st, 2020 (edited)
1,609
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. import org.apache.commons.lang3.ArrayUtils;
  2.  
  3. public class Insertion {
  4.     static void print(Comparable[] a) {
  5.         for (Comparable i : a) System.out.print(i + " ");
  6.         System.out.println();
  7.     }
  8.  
  9.     static void swap(Comparable [] a, int p, int q) {
  10.         Comparable temp = a[p];
  11.         a[p] = a[q];
  12.         a[q] = temp;
  13.     }
  14.  
  15.     static boolean less(Comparable a, Comparable b) {
  16.         return a.compareTo(b) < 0;
  17.     }
  18.  
  19.     public static boolean isSorted(Comparable[] a) {
  20.         for (int i = 1; i < a.length; i++) {
  21.             if (less(a[i], a[i - 1])) return false;
  22.         }
  23.         return true;
  24.     }
  25.  
  26.     public static void sort(Comparable[] a) {
  27.         for (int i = 1; i < a.length; i++) {
  28.             for (int j = i; j > 0; j--) {
  29.                 if (a[j].compareTo(a[j - 1]) < 0){
  30.                     swap(a, j, j - 1);
  31.                     print(a);
  32.                 }
  33.                 else break;
  34.             }
  35.         }
  36.     }
  37.  
  38.     public static void main(String[] args) {
  39.         String s = "SHELLSORTEXAMPLE";
  40.         Character[] a= ArrayUtils.toObject(s.toCharArray());
  41. //        Integer[] a = new Integer[]{31, 41, 59, 26, 41, 58};
  42.         print(a);
  43.         sort(a);
  44.         if (!isSorted(a)) throw new AssertionError("Array not sorted");
  45.         print(a);
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement