直接插入排序练习:POJ 2388
关于直接插入排序请参看:http://128kj.iteye.com/blog/1662280
POJ2388题意:
【输入】第一行为n,接下来n行分别为一个数;
【输出】这n个数排序后的中位数
样例:
Sample Input
5
2
4
1
3
5
Sample Output
3
分析:好象用多种排序法都可以AC,前面用了堆排序,这里再用直接插入排序,主要是复习一下代码。比起堆排序,代码短多了。
排一次序后输出中位数,但效率太低了。这里先不管了。
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int[] array =new int[n]; for(int i=0;i<n;i++) array[i]=in.nextInt(); sort(array); System.out.println(array[n / 2 ]); //for(int el : array) { // System.out.print(el + " "); //} } static void sort(int[] array) { int temp; int i,j; int length = array.length; for(i = 1; i < length; i++) { temp = array[i]; for(j = i-1; j >=0; j--) { if(temp < array[j]) { array[j+1] = array[j]; } else { break; } } array[j+1] = temp; } } }