Advertisement
Guest User

InsertionSort

a guest
Mar 26th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.87 KB | None | 0 0
  1. import java.util.Comparator;
  2.  
  3. public class InsertionSort {
  4.  
  5.     private static Comparator c;
  6.  
  7.     private static boolean less(Comparable v, Comparable w){
  8.         return c.compare(v, w)<0;
  9.     }
  10.  
  11.     private static void exch(Comparable[] a, int i, int j){
  12.         Comparable swap = a[i];
  13.         a[i] = a[j];
  14.         a[j] = swap;
  15.     }
  16.    
  17.     private static boolean isSorted(Comparable[] a){
  18.         for (int i=1;i<a.length;i++)
  19.             if (less(a[i],a[i-1])) return false;
  20.         return true;
  21.     }
  22.  
  23.     public static void sort(Comparable[] a, Comparator y){
  24.         c = y;
  25.         int n = a.length;
  26.         for (int i=0;i<n;i++){
  27.             for (int j = i;j>0;j--)
  28.                 if (less(a[j],a[j-1]))
  29.                     exch(a,j,j-1);
  30.                 else break;
  31.         }
  32.     }
  33.     public static void sort(Comparable[] a, int l, int h, Comparator y){
  34.         c = y;
  35.         for (int i=l;i<=h;i++){
  36.             for (int j = i;j>0;j--)
  37.                 if (less(a[j],a[j-1]))
  38.                     exch(a,j,j-1);
  39.                 else break;
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement