您的位置:首页 > 编程语言 > Java开发

java 插入排序

2016-06-13 13:23 344 查看
一、插入排序的规则
1.从1开始增量为1
2.需要记录被排序的数据
3.记录被排序数据应该插入的位置
4.前面的数据(已排序)只要是比被排序的数据大,都往后移,直到比它大或相等才停止比较(停止的位置下标就是被排序数据的位置).
5.将被排序的数据插入到对应的位置

二、代码实例
public class InsertSort
{
public static void main(String[] args)
{

long[] testArr = new long[]{ 111, 3, 5, 3456, 33, 2, 899, 1, 5 };
long tempLong; //被排序数据临时变量
int tempInt; // 插入位置的临时变量
for(int i = 1 ; i < testArr.length;i++)
{
tempLong = testArr[i]; // 备份被排序的数据
tempInt = i; // 记录被排序的数据位置
//前面的数据(已排序)只要是比被排序的数据大,都往后移,直到比它大或相等才停 //止比较(停止的位置下标就是被排序数据的位置).
while(tempInt > 0 && testArr[tempInt - 1] > tempLong )
{
testArr[tempInt] = testArr[tempInt - 1];
--tempInt; // 数据位置往前移
}
testArr[tempInt] = tempLong;
}

// 打印排序后的数据
for(int i = 1 ; i < testArr.length;i++)
System.out.println(testArr[i]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 基础