Advertisement
KechevD

Kursova2_SELECTION SORTandSHELLSORT

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