JAVA排序算法实现代码-插入排序

插入排序算法步骤
1.从有序数列和无序数列{a2,a3,…,an}开始进行排序;
2.处理第i个元素时(i=2,3,…,n) , 数列{a1,a2,…,ai-1}是已有序的,而数列{ai,ai+1,…,an}是无序的。用ai与ai-1,a i-2,…,a1进行比较,找出合适的位置将ai插入;
3.重复第二步,共进行n-1次插入处理,数列全部有序。

我的做法(感觉代码有点乱)

import java.util.ArrayList;
import java.util.List;

public class InsertSort {
public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组

public static void main(String[] args){
List list = new ArrayList();
for(int jj : a){
InsertSort(a);
list.add(a[a.length-1]);
a[a.length-1] = 0;
}
for(int ee =0;ee<list.size();ee++){
System.out.println(list.get(ee));
}
System.out.println();
}
public static void InsertSort(int[] a){

List listSource = new ArrayList();
int tmp = 0;
for(int j=0 ; j<a.length; j++){
if(j == a.length-1){
continue;
}
if(a[j]>a[j+1])
{
tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
System.out.println("The biggest is : "+ a[a.length-1]);
}

}



参考一下网上的例子 :


public class Test {
public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组

public static void main(String args[]) {
int i; // 循环计数变量
int Index = a.length;// 数据索引变量

System.out.print("排序前: ");
for (i = 0; i < Index - 1; i++)
System.out.print(" " + a[i] + " ");
System.out.println("");

InsertSort(Index - 1); // 选择排序
// 排序后结果
System.out.print("排序后: ");
for (i = 0; i < Index - 1; i++)
System.out.print(" " + a[i] + " ");
System.out.println("");
}

public static void InsertSort(int Index) {
int i, j, k; // 循环计数变量
int InsertNode; // 欲插入数据变量

for (i = 1; i < Index; i++) // 依序插入数值
{
InsertNode = a[i]; // 设定欲插入的数值
j = i - 1; // 欲插入数组的开始位置
// 找适当的插入位置
while (j >= 0 && InsertNode < a[j]) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = InsertNode; // 将数值插入
// 打印目前排序结果
System.out.print("排序中: ");
for (k = 0; k < Index; k++)
System.out.print(" " + a[k] + " ");
System.out.println("");
}
}
}


运行结果
排序前: 10 32 1 9 5 7 12 0 4
排序中: 10 32 1 9 5 7 12 0 4
排序中: 1 10 32 9 5 7 12 0 4
排序中: 1 9 10 32 5 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 7 9 10 32 12 0 4
排序中: 1 5 7 9 10 12 32 0 4
排序中: 0 1 5 7 9 10 12 32 4
排序中: 0 1 4 5 7 9 10 12 32
排序后: 0 1 4 5 7 9 10 12 32

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值