堆排序练习:POJ 2388

来源:互联网 发布:ios 本地存储数组 编辑:程序博客网 时间:2024/06/14 14:28
关于堆排序请参看:http://128kj.iteye.com/blog/1679094
POJ2388题意:
【输入】第一行为n,接下来n行分别为一个数;
【输出】这n个数排序后的中位数
样例:
Sample Input

5
2
4
1
3
5
Sample Output

3

分析:好象用多种排序法都可以AC,这里先用堆排序,主要是复习一下堆排序代码。

排一次序后输出中位数,但效率太低了。这里先不管了。


Java代码 复制代码 收藏代码
  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner in=new Scanner(System.in);
  5. int n=in.nextInt();
  6. int[] array =new int[n+1];
  7. // array[0]=100; 不参与,下标从1开始
  8. for(int i=1;i<=n;i++)
  9. array[i]=in.nextInt();
  10. heapSort(array);//堆排序
  11. System.out.println(array[n / 2+1 ]);
  12. //堆排序的结果
  13. // for(int i=1;i<=n;i++)
  14. // System.out.print(array[i]+" ");
  15. }
  16. //把a,b位置的值互换
  17. public static void swap(int[] array, int a, int b) {
  18. //临时存储child位置的值
  19. int temp = array[a];
  20. array[a]=array[b];
  21. array[b]=temp;
  22. }
  23. /*将数组调整成堆
  24. *根据树的性质建堆,树节点前一半一定是分支节点,即有孩子的,所以我们从这里开始调整出初始堆
  25. */
  26. public static void adjust(int[] array){
  27. for (int i = array.length /2; i > 0; i--)
  28. adjust(array,i, array.length-1);
  29. }
  30. /**
  31. * 调整堆,使其满足堆得定义
  32. * @param i
  33. * @param n
  34. */
  35. public static void adjust(int[] array,int i,int n) {
  36. int child;
  37. for (; i <= n / 2; ) {
  38. child = i * 2;
  39. if(child+1<=n&&array[child]<array[child+1])
  40. child+=1;/*使child指向值较大的孩子*/
  41. if(array[i]< array[child]){
  42. swap(array,i, child);
  43. /*交换后,以child为根的子树不一定满足堆定义,所以从child处开始调整*/
  44. i = child;
  45. } else break;
  46. }
  47. }
  48. //对一个最大堆heap排序
  49. public static void heapSort(int[] array) {
  50. adjust(array);//建堆
  51. for (int i = array.length-1; i >0; i--) {
  52. /*把根节点跟最后一个元素交换位置,调整剩下的n-1个节点,即可排好序*/
  53. swap(array,1, i);
  54. adjust(array,1, i - 1);
  55. }
  56. }
  57. }    
原创粉丝点击