m2skills

shell java

Apr 4th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3.  
  4. import static java.lang.System.*;
  5.  
  6. /**
  7.  * Created by MOHIT on 31-12-2016.
  8.  */
  9.  
  10. public class shell {
  11.     public static void main(String arg[]) {
  12.         Scanner sc  = new Scanner(in);
  13.         System.out.print("Enter the Array to be sorted : ");
  14.         String str1 = sc.next();
  15.         String[] strArr = str1.split(",");
  16.        
  17.         int[] numbers = new int[strArr.length];
  18.         int i=0;
  19.        
  20.         for (String str2 :strArr) {
  21.             int temp = Integer.parseInt(str2);
  22.             numbers[i] = temp;
  23.             i++;
  24.         }
  25.         numbers = shellSort(numbers);
  26.  
  27.         System.out.println("The Array after sorting is : ");
  28.         for(i=0; i<numbers.length; i++){
  29.             System.out.print(numbers[i] + " ");
  30.         }
  31.     }
  32.    
  33.     private static int[] shellSort(int[] numbers){
  34.         int gap = numbers.length / 2;
  35.        
  36.         while (gap > 0){
  37.             // loop till i is in range from gaps to lenght of the list
  38.             for (int i = 0; i < numbers.length; i++){
  39.                 // store the ith element in the temp variable
  40.                 int temp = numbers[i];
  41.                 int j = i;
  42.                 // applying insertion sort on the sublist
  43.                 // shifting the elements larger than the ith element to the right
  44.                 while(j >= gap && numbers[j - gap] > temp){
  45.                     numbers[j] = numbers[j - gap];
  46.                     j -= gap;
  47.                 }  
  48.                 // puting the element at its correct position  
  49.                 numbers[j] = temp;
  50.             }  
  51.             // reduce gap by it half   
  52.             gap = gap/2;
  53.         }  
  54.         return numbers;
  55.     }
  56. }
  57.  
  58. /*
  59.  
  60. Enter the Array to be sorted : 231,3423,35,12,34,54,12,5
  61. The Array after sorting is :
  62. 5 12 12 34 35 54 231 3423
  63.  
  64. */
Add Comment
Please, Sign In to add comment