插入排序:插入排序是在遍历元素的过程中,当前索引左边的所有元素都是有序的,但最终位置是不确定的;当前索引右边的所有元素都是待排序的,而排序的过程就是逐渐将索引右边的无序的元素按照自己制定的排序规则插入到索引左边的有序的元素中,当索引到达数组的右端时,数组的排序就完成了。
在算法第四版中给出的所有排序均是适用于任意实现了Comparable接口的数据类型,若要将数字作为测试用例,请勿使用基本数据类型,改用Integer等实现了Comparable接口的对象。
代码如下:
/**
*
* @author Administrator
* @Description
* 插入排序是在遍历元素的过程中,当前索引左边的所有元素都是有序的,但最终位置是不确定的;
* 当前索引右边的所有元素都是待排序的,
* 而排序的过程就是逐渐将索引右边的无序的元素按照自己制定的排序规则插入到索引左边的有序的元素中,
* 当索引到达数组的右端时,数组的排序就完成了。
*
*/
public class InsertionSort {
public static void sort(Comparable[] a)
{
int N = a.length;
for(int i = 0; i < N; i++)
{
for(int j = i; j > 0 && less(a[j],a[j-1]); j--)
{
exch(a,j,j-1);
}
}
}
public static boolean less(Comparable v, Comparable w)
{
return v.compareTo(w) < 0;
}
public static void exch(Comparable[] a,int i,int j)
{
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean isSort(Comparable[] a)
{
for(int i = 1; i < a.length; i++)
{
if(less(a[i],a[i-1]))
{
return false;
}
}
return true;
}
public static void show(Comparable[] a)
{
for(int i = 0 ; i < a.length ; i++)
{
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void main(String[] args)
{
Integer[] nums = new Integer[10];
for(int i = 0; i < 10; i++)
{
nums[i] = (int)(Math.random() * 10 + 1);
System.out.print(nums[i] + " ");
}
System.out.println();
sort(nums);
assert isSort(nums);
show(nums);
}
}