直接插入排序
核心思想:i从第二位元素开始,将数据插入左侧有序数列中,左侧大于该数的元素右移。
直接插入排序的实现:
package Straight_Insertion_Sort; public class StraightInsertionSort { public int[] a=new int[11]; public int size; public int i,j; public StraightInsertionSort(int[] a) { for(int i=0;i<a.length;i++) { this.a[i+1]=a[i]; } size=this.a.length; } public void straightInsertionSort() { for(i=2;i<size;i++) { if(a[i]<a[i-1]) { a[0]=a[i]; for(j=i-1;a[j]>a[0];j--) { a[j+1]=a[j]; } a[j+1]=a[0]; } } } //遍历 public void traversal() { for(int i=1;i<size;i++) { System.out.println(a[i]); } } //交换 public void swap(int[] arr,int a,int b) { arr[a] = arr[a]+arr[b]; arr[b] = arr[a]-arr[b]; arr[a] = arr[a]-arr[b]; } }
测试:
package Straight_Insertion_Sort; public class App { public static void main(String[] args) { // TODO Auto-generated method stub int[] a={6,21,3,99,56,44,77,12,7,19}; StraightInsertionSort sort=new StraightInsertionSort(a); sort.straightInsertionSort(); sort.traversal(); } }
结果:
3 6 7 12 19 21 44 56 77 99