ShellSort.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Java implementation of ShellSort
  2. // https://www.geeksforgeeks.org/shell-sort/
  3. class ShellSort
  4. {
  5. /* An utility function to print array of size n*/
  6. static void printArray(int arr[])
  7. {
  8. int n = arr.length;
  9. for (int i=0; i<n; ++i)
  10. System.out.print(arr[i] + " ");
  11. System.out.println();
  12. }
  13. /* function to sort arr using shellSort */
  14. int sort(int arr[])
  15. {
  16. int n = arr.length;
  17. // Start with a big gap, then reduce the gap
  18. for (int gap = n/2; gap > 0; gap /= 2)
  19. {
  20. // Do a gapped insertion sort for this gap size.
  21. // The first gap elements a[0..gap-1] are already
  22. // in gapped order keep adding one more element
  23. // until the entire array is gap sorted
  24. for (int i = gap; i < n; i += 1)
  25. {
  26. // add a[i] to the elements that have been gap
  27. // sorted save a[i] in temp and make a hole at
  28. // position i
  29. int temp = arr[i];
  30. // shift earlier gap-sorted elements up until
  31. // the correct location for a[i] is found
  32. int j;
  33. for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
  34. arr[j] = arr[j - gap];
  35. // put temp (the original a[i]) in its correct
  36. // location
  37. arr[j] = temp;
  38. }
  39. }
  40. return 0;
  41. }
  42. // Driver method
  43. public static void main(String args[])
  44. {
  45. int arr[] = {12, 34, 54, 2, 3};
  46. System.out.println("Array before sorting");
  47. printArray(arr);
  48. ShellSort ob = new ShellSort();
  49. ob.sort(arr);
  50. System.out.println("Array after sorting");
  51. printArray(arr);
  52. }
  53. }
  54. /*This code is contributed by Rajat Mishra */