直接插入排序练习:POJ 2388
2013-02-19 20:59
267 查看
关于直接插入排序请参看:http://128kj.iteye.com/blog/1662280
POJ2388题意:
【输入】第一行为n,接下来n行分别为一个数;
【输出】这n个数排序后的中位数
样例:
Sample Input
5
2
4
1
3
5
Sample Output
3
分析:好象用多种排序法都可以AC,前面用了堆排序,这里再用直接插入排序,主要是复习一下代码。比起堆排序,代码短多了。
排一次序后输出中位数,但效率太低了。这里先不管了。
Java代码
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
;
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;
}
}
}
POJ2388题意:
【输入】第一行为n,接下来n行分别为一个数;
【输出】这n个数排序后的中位数
样例:
Sample Input
5
2
4
1
3
5
Sample Output
3
分析:好象用多种排序法都可以AC,前面用了堆排序,这里再用直接插入排序,主要是复习一下代码。比起堆排序,代码短多了。
排一次序后输出中位数,但效率太低了。这里先不管了。
Java代码
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
;
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;
}
}
}
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 ; 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; } } }
相关文章推荐
- 直接插入排序练习:POJ 2388
- C语言 指针练习-直接插入排序法
- 直接插入排序 练习
- 堆排序练习:POJ 2388
- 堆排序练习:POJ 2388
- Scala练习-直接插入排序
- 排序算法-直接插入排序
- 插入排序(直接插入排序,折半插入排序,2路插入排序,希尔排序)
- 希尔排序(及其与直接插入排序的区别)
- 算法之直接插入排序和希尔排序
- 排序--直接插入排序思想及代码实现
- 直接插入排序
- 常用排序算法之插入排序 ( 直接插入排序、希尔排序 )
- poj 2388 Who's in the Middle(快速排序求中位数)
- 直接插入排序
- 白话经典算法系列之二 直接插入排序的三种实现
- 【排序算法】直接插入排序
- 直接插入排序(Straight Insertion Sort)
- 排序算法-插入排序之直接插入
- 直接插入排序的三种实现