Advertisement
16225

3.5

Jun 16th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. package KursovaRabotaSrok2;
  2. import java.util.Arrays;
  3. public class SelectionVsShellSort2 {
  4.  
  5.     public static void main(String[] args) {
  6.         int[] arr = new int[]{233, 1, 5, 99, 17, 4};
  7.         System.out.println(Arrays.toString(shellSort(arr, arr.length)));
  8.         System.out.println(Arrays.toString(sort(arr)));
  9.         /*
  10.        Shell heapSort has better time complexity O(n log(n))
  11.        and they have same space complexity O(1)
  12.          */
  13.     }
  14. ________________________________________________
  15. static int[] shellSort(int arr[], int n) {
  16.         // Start with a big gap, then reduce the gap
  17.         for (int gap = n / 2; gap > 0; gap /= 2) {
  18.             // Do a gapped insertion heapSort for this gap size.
  19.             // The first gap elements a[0..gap-1] are already in gapped order
  20.             // keep adding one more element until the entire array is
  21.             // gap sorted
  22.             for (int i = gap; i < n; i += 1) {
  23.                 // add a[i] to the elements that have been gap sorted
  24.                 // save a[i] in temp and make a hole at position i
  25.                 int temp = arr[i];
  26.                 // shift earlier gap-sorted elements up until the correct
  27.                 // location for a[i] is found
  28.                 int j;
  29.                 for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
  30.                     arr[j] = arr[j - gap];
  31.                 }
  32.                 //  put temp (the original a[i]) in its correct location
  33.                 arr[j] = temp;
  34.             }
  35.         }
  36.         return arr;
  37.     }
  38.     static int[] sort(int arr[]) {
  39.         int n = arr.length;
  40.         // One by one move boundary of unsorted subarray
  41.         for (int i = 0; i < n - 1; i++) {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement