/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package test;
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
*
* @author leo
*/
public class Test {
/**
* @param args the command line arguments
*/
public static int a[];//元素数组
public static int n;//数组大小
public static long st,ed;//起始时间,结束时间
/*插入排序*/
public static void insert_sort(int x) {
a[0] = a[x];
int j = x-1;
while(a[0]<a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = a[0];
}
/*冒泡排序*/
public static void bubble_sort() {
int i,j;
for (i=1; i+1<=n; i++) {
for (j=1; j<=n-i; j++) {
if (a[j] > a[j+1]) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
/*选择排序*/
public static void select_sort() {
int i,j;
for (i=1; i+1<=n; i++) {
int k = i;
for (j=i+1; j<=n; j++) {
if (a[j] < a[k])k = j;
}
if (i != k) {
int tmp = a[i];
a[i] = a[k];
a[k] = tmp;
}
}
}
/*此方法输出排序后数组和算法运行时间*/
public static void output() {
System.out.println("排序后的数组是(排序所消耗的时间是"+(ed - st)+"纳秒):");
for(int i=1; i<=n; i++)System.out.printf(a[i]+" ");
System.out.println("");
}
public static void main(String[] args) {
System.out.print("请输入待排序数组个数n【退出请按0】:");
boolean flag;
flag = false;
Scanner cin = new Scanner(new BufferedInputStream(System.in));
while(true) {
if(flag)System.out.print("请输入待排序数组个数n【退出请按0】:");
n = cin.nextInt();
if(n==0)break;
int tmp[] = new int[n+2];
a = new int[n+2];
System.out.println("请输入n个元素(以enter结束):");
for(int i=1; i<=n; i++) {
tmp[i] = cin.nextInt();
}
int choice;
System.out.println("请输入排序算法种类:1、插入排序 2、冒泡排序 3、直接选择排序 0、返回上一层:");
while(true) {
choice = cin.nextInt();
flag = true;
if(choice==0)break;
switch(choice) {
case 1:
for(int i=1; i<=n; i++) {
a[i] = tmp[i];
}
st = System.nanoTime();
for(int i=1; i<=n; i++) insert_sort(i);
ed = System.nanoTime();
output();
break;
case 2:
for(int i=1; i<=n; i++)a[i] = tmp[i];
st = System.nanoTime();
bubble_sort();
ed = System.nanoTime();
output();
break;
case 3:
for(int i=1; i<=n; i++)a[i] = tmp[i];
st = System.nanoTime();
select_sort();
ed = System.nanoTime();
output();
break;
case 0:break;
}
}
}
}
}
java
最新推荐文章于 2024-11-28 19:42:44 发布