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

Java排序算法优化--插入排序【温故而知新】

2014-04-16 17:00 113 查看
/**
*
* @author Fly
*/
public class InsertSort {

public int[] insertSort(int[] a) {
int size = a.length;
int j;
for (int i = 1; i < size; i++) {
int temp = a[i];
for (j = 0; j < i; j++) {
if (a[i] < a[j]) {
break;
}
}
for (int k = i; k > j; k--) {
a[k] = a[k - 1];
}
a[j] = temp;
}
return a;
}

public int[] insertSort1(int[] a) {
int size = a.length;
for (int i = 1; i < size; i++) {
//标记当前需要比较的元素,也就是当前无序数组中的第一个元素
//j是有序数组中小于a[i]的元素
int temp = a[i], j;
//循环继续的条件就是遇到比a[i]大的元素,如果没有了,说明找到了正确的位置
for (j = i; j > 0 && temp < a[j - 1]; j--) {
a[j] = a[j - 1];
}
//把a[i]的值给找到的那个元素
a[j] = temp;
//其实这是一个连续交换的过程
}
return a;
}

public void printArray(int[] a) {
for (int i : a) {
System.out.print(i + ",");
}
System.out.println();
}

public static void main(String[] args) {
int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6};
InsertSort insertSort = new InsertSort();
insertSort.printArray(a);
insertSort.printArray(insertSort.insertSort(a));
insertSort.printArray(insertSort.insertSort1(a));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: