直接插入排序练习:POJ 2388

来源:互联网 发布:积分商城数据分析 编辑:程序博客网 时间:2024/06/07 07:15
关于直接插入排序请参看:http://128kj.iteye.com/blog/1662280

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];
  7. for(int i=0;i<n;i++)
  8. array[i]=in.nextInt();
  9. sort(array);
  10. System.out.println(array[n / 2 ]);
  11. //for(int el : array) {
  12. // System.out.print(el + " ");
  13. //}
  14. }
  15. static void sort(int[] array) {
  16. int temp;
  17. int i,j;
  18. int length = array.length;
  19. for(i = 1; i < length; i++) {
  20. temp = array[i];
  21. for(j = i-1; j >=0; j--) {
  22. if(temp < array[j]) {
  23. array[j+1] = array[j];
  24. } else {
  25. break;
  26. }
  27. }
  28. array[j+1] = temp;
  29. }
  30. }
  31. }

原创粉丝点击