平时见得比较多的稳定的排序是冒泡排序
/*
* 冒泡排序
*/
public class bubblesort {
public static void main(String[] args) {
int[] arr={6,3,8,2,9,1};
System.out.println("排序前数组为:");
for(int num:arr){
System.out.print(num+" ");
}
for(int i=0;i<arr.length-1;i++){//外层循环控制排序趟数
for(int j=0;j<arr.length-1-i;j++){//内层循环控制每一趟排序多少次
if(arr[j]<arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println();
System.out.println("排序后的数组为:");
for(int num:arr){
System.out.print(num+" ");
}
}
}
第一遍尝试,没有AC 但我在我的eclipse上运行例子,结果是正确的呀
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/*
* 冒泡排序
*/
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int type=sc.nextInt();
// String name[]= {};
// int score[]=new int[n];
// for(int i=0;i<n;i++)
// {
// name[i]=sc.next();
// score[i]=sc.nextInt();
// } 这种方法行不通
//换一种一次读一行的方法 然后按空格分开
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String name[]=new String[n];
int score[]=new int[n];
String []parts = null;
for(int i=0;i<n;i++)
{
String line=reader.readLine();
parts=line.split(" ");
String thisname=parts[0];
int thisscore=Integer.parseInt(parts[1]);
name[i]=thisname;
// name=insert(name, thisname);
score[i]=thisscore;
// System.out.println(parts[0]);
}
/* System.out.println(parts[0]);
System.out.println(parts[1]);*/
/*System.out.println("排序前数组为:");
for(int num:score){
System.out.print(num+" ");
}*/
if(type==0) {
for(int i=0;i<score.length-1;i++){//外层循环控制排序趟数
for(int j=0;j<score.length-1-i;j++){//内层循环控制每一趟排序多少次
if(score[j]<score[j+1]){
int temp=score[j];
score[j]=score[j+1];
score[j+1]=temp;
String t=name[j];
name[j]=name[j+1];
name[j+1]=t;
}
}
}
// System.out.println();
// System.out.println("排序后名字为:");
/* for(String num:name){
System.out.print(num+" ");
}
System.out.println("排序后的数组为:");
for(int num:score){
System.out.print(num+" ");
} */
for(int i=0;i<n;i++)
{
System.out.println(name[i]+" "+score[i]);
}
}
if(type==1) {
for(int i=0;i<score.length-1;i++){//外层循环控制排序趟数
for(int j=0;j<score.length-1-i;j++){//内层循环控制每一趟排序多少次
if(score[j]>score[j+1]){
int temp=score[j];
score[j]=score[j+1];
score[j+1]=temp;
String t=name[j];
name[j]=name[j+1];
name[j+1]=t;
}
}
}
/* System.out.println();
System.out.println("排序前名字为:");
for(String num:name){
System.out.print(num+" ");
}
System.out.println("排序后的数组为:");
for(int num:score){
System.out.print(num+" ");
} */
for(int i=0;i<n;i++)
{
System.out.println(name[i]+" "+score[i]);
}
}
}
// TODO Auto-generated method stub
private static String[] insert(String[] arr, String str) {
int size = arr.length; //获取数组长度
String[] tmp = new String[size + 1]; //新建临时字符串数组,在原来基础上长度加一
for (int i = 0; i < size; i++){ //先遍历将原来的字符串数组数据添加到临时字符串数组
tmp[i] = arr[i];
}
tmp[size] = str; //在最后添加上需要追加的数据
return tmp; //返回拼接完成的字符串数组
}
}
运行结果
先mark,明日再试。