Advertisement
santiagol26

HeapShort

Oct 21st, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /* Class HeapSort */
  4. public class HeapSort
  5. {
  6. private static int N;
  7. /* Sort Function */
  8. public static void sort(int arr[])
  9. {
  10. heapify(arr);
  11. for (int i = N; i > 0; i--)
  12. {
  13. swap(arr,0, i);
  14. N = N-1;
  15. maxheap(arr, 0);
  16. }
  17. }
  18. /* Function to build a heap */
  19. public static void heapify(int arr[])
  20. {
  21. N = arr.length-1;
  22. for (int i = N/2; i >= 0; i--)
  23. maxheap(arr, i);
  24. }
  25. /* Function to swap largest element in heap */
  26. public static void maxheap(int arr[], int i)
  27. {
  28. int left = 2*i ;
  29. int right = 2*i + 1;
  30. int max = i;
  31. if (left <= N && arr[left] > arr[i])
  32. max = left;
  33. if (right <= N && arr[right] > arr[max])
  34. max = right;
  35.  
  36. if (max != i)
  37. {
  38. swap(arr, i, max);
  39. maxheap(arr, max);
  40. }
  41. }
  42. /* Function to swap two numbers in an array */
  43. public static void swap(int arr[], int i, int j)
  44. {
  45. int tmp = arr[i];
  46. arr[i] = arr[j];
  47. arr[j] = tmp;
  48. }
  49. /* Main method */
  50. public static void main(String[] args)
  51. {
  52. Scanner scan = new Scanner( System.in );
  53. System.out.println("Heap Sort Test\n");
  54. int n, i;
  55. /* Accept number of elements */
  56. System.out.println("Enter number of integer elements");
  57. n = scan.nextInt();
  58. /* Make array of n elements */
  59. int arr[] = new int[ n ];
  60. /* Accept elements */
  61. System.out.println("\nEnter "+ n +" integer elements");
  62. for (i = 0; i < n; i++)
  63. arr[i] = scan.nextInt();
  64. /* Call method sort */
  65. sort(arr);
  66. /* Print sorted Array */
  67. System.out.println("\nElements after sorting ");
  68. for (i = 0; i < n; i++)
  69. System.out.print(arr[i]+" ");
  70. System.out.println();
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement