插入排序

来源:互联网 发布:选5型5中5旋转矩阵公式 编辑:程序博客网 时间:2024/05/05 12:08
//插入排序,稳定, 时间复杂度为O(n^2)import java.util.Arrays;public class InsertSortTest {/*public static void InsertSort(int[] a){//非降序int j;for(int i = 1;i < a.length;i++ ){int temp = a[i];for(j = i; j > 0;j--)if(temp < a[j-1])a[j] = a[j-1];a[j] = temp;}}*//*public static void InsertSort(int[] a){//非升序int j;for(int i = 1;i<a.length;i++){int temp = a[i];for(j = i;j>0;j--){if(temp>a[j-1])a[j] = a[j-1];}a[j] = temp;}}*/
//JAVA泛型/*public static <AnyType extends Comparable<? super AnyType>>void InsertSort(AnyType a[]){int j;for(int i = 1;i < a.length; i++){AnyType temp = a[i];for(j = i;j > 0&&(temp.compareTo(a[j-1])) > 0;j--)a[j]  = a[j-1];a[j] = temp;}}*///二分插入排序public static void InsertSort(int a[]){int j;for(int i = 1;i < a.length; i++){int temp = a[i];int left = 0;int right = i-1;while(left<=right){int mid = (left + right) / 2;if(temp<=a[mid])right = mid - 1;elseleft = mid + 1;}for(j = i-1;j >= right + 1;--j)a[j+1] = a[j];a[right+1] = temp;}}public static void main(String[] args){int[] a = new int[]{5,4,3,2,1,7};InsertSort(a);System.out.println(Arrays.toString(a));}}


                                             
0 0
原创粉丝点击