Advertisement
steakzond

InsertBinarSort

Dec 22nd, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. import java.util.*;
  2. public class InsertionSort {
  3.     public static int [] sort(int [] a, int j){
  4.         int nb = j;
  5.         int nm = 0;
  6.         int p = a[j];
  7.         while (nm < nb){
  8.             int mid = (nm + nb) / 2;
  9.             if (p < a[mid]){
  10.                 nb = mid;
  11.             }
  12.             else{
  13.                 nm = mid + 1;
  14.             }
  15.         }
  16.         for (int i = nm; i <= j; i++){
  17.             int hm =a [i];
  18.             int k = i - 1;
  19.             while ( k >= nm && a[k] > hm){
  20.                 a[k + 1] = a[k];
  21.                 a[k] = hm;
  22.                 k--;
  23.             }
  24.         }
  25.    
  26.         return a;
  27.     }
  28.     public static void main(String[] args) {
  29.         Scanner sc = new Scanner(System.in);
  30.         System.out.print("Enter a number: ");
  31.         int n = sc.nextInt();
  32.         int [] a = new int[n];
  33.         a[0] = sc.nextInt();
  34.         for (int i = 1; i < n; i++){
  35.             a[i] = sc.nextInt();
  36.             a = sort(a, i);
  37.         }
  38.         for (int i = 0; i < n; i++){
  39.             System.out.print(a[i] + " ");
  40.         }
  41.  
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement