fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static void sink(int [] A, int i, int n) {
  11. int highest = 2*i+1;
  12. if (2*i+1 >= n)
  13. return;
  14. if (2*i+2 < n && A[2*i+2] > A[highest])
  15. ++highest;
  16. if (A[i] < A[highest]) {
  17. int tmp = A[i];
  18. A[i] = A[highest];
  19. A[highest] = tmp;
  20. sink(A, highest, n);
  21. }
  22. }
  23.  
  24. static void heapify(int [] A, int n) {
  25. for (int i = n/2; i >= 0; --i) {
  26. sink(A, i, n);
  27. }
  28. }
  29. public static void main (String[] args) throws java.lang.Exception
  30. {
  31. // your code goes here
  32. int[] arr = new int[] {4, 8, 3, 1, 12, 15, 25, 11, 5, 6};
  33. heapify(arr, arr.length);
  34. for(int i = 0; i < arr.length; ++i) {
  35. System.out.println(arr[i]);
  36. }
  37. }
  38. }
Success #stdin #stdout 0.09s 320320KB
stdin
Standard input is empty
stdout
25
12
15
11
8
4
3
1
5
6