插入排序
插入时比较元素后需要考虑向后移动元素
要用temp原因是因为插入过程中a[j+1]会把a[i]里面的元素替换掉
package Week1;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class bubbleSorted {
public static void main(String[] args) throws IOException {
BufferedReader inputStream=new BufferedReader(new InputStreamReader(System.in));
String b;
while((b=inputStream.readLine())!=null){
//String[] aStrings=b.split(" ");
//int nums=Integer.parseInt(inputStream.readLine());
//for(int num=0;num<nums;num++){
// b=inputStream.readLine();
String[] aStrings=b.split(" ");
Integer alength=Integer.parseInt(aStrings[0]);
int[] a=new int[alength];
for(int i=1;i<aStrings.length;i++){
a[i-1]=Integer.parseInt(aStrings[i]);
}
if(a.length>1){
insertSorted(a);
}
print(a);
System.out.println();
}
}
private static void insertSorted(int[] a) {
// TODO Auto-generated method stub
int temp=0;//要用temp原因是因为插入过程中a[j+1]会把a[i]里面的元素替换掉
int j=0;
for(int i=1;i<a.length;i++){
temp=a[i];
for(j=i-1;j>=0;){
if(temp<a[j]){
a[j+1]=a[j];
j--;
}else
break;
}
a[j+1]=temp;
}
}
//按格式打印
private static void print(int[] a) {
// TODO Auto-generated method stub
if(a.length==1)
System.out.print(a[0]);
else {
System.out.print(a[0]);
for(int i=1;i<a.length;i++){
System.out.print(" "+a[i]);
}
}
}
}