package com.sort; 2 3 public class 直接插入排序 { 4 5 public static void main(String[] args) { 6 int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1}; 7 System.out.println("排序之前:"); 8 for (int i = 0; i < a.length; i++) { 9 System.out.print(a[i]+" "); 10 } 11 //直接插入排序 12 for (int i = 1; i < a.length; i++) { 13 //待插入元素 14 int temp = a[i]; 15 int j; 16 /*for (j = i-1; j>=0 && a[j]>temp; j--) { 17 //将大于temp的往后移动一位 18 a[j+1] = a[j]; 19 }*/ 20 for (j = i-1; j>=0; j--) { 21 //将大于temp的往后移动一位 22 if(a[j]>temp){ 23 a[j+1] = a[j]; 24 }else{ 25 break; 26 } 27 } 28 a[j+1] = temp; 29 } 30 System.out.println(); 31 System.out.println("排序之后:"); 32 for (int i = 0; i < a.length; i++) { 33 System.out.print(a[i]+" "); 34 } 35 } 36 37 } 复制代码 package com.sort; 2 3 public class 二分插入排序 { 4 public static void main(String[] args) { 5 int[] a={49,38,65,97,176,213,227,49,78,34,12,164,11,18,1}; 6 System.out.println("排序之前:"); 7 for (int i = 0; i < a.length; i++) { 8 System.out.print(a[i]+" "); 9 } 10 //二分插入排序 11 sort(a); 12 System.out.println(); 13 System.out.println("排序之后:"); 14 for (int i = 0; i < a.length; i++) { 15 System.out.print(a[i]+" "); 16 } 17 } 18 19 private static void sort(int[] a) { 20 for (int i = 0; i < a.length; i++) { 21 int temp = a[i]; 22 int left = 0; 23 int right = i-1; 24 int mid = 0; 25 while(left<=right){ 26 mid = (left+right)/2; 27 if(temp<a[mid]){ 28 right = mid-1; 29 }else{ 30 left = mid+1; 31 } 32 } 33 for (int j = i-1; j >= left; j--) { 34 a[j+1] = a[j]; 35 } 36 if(left != i){ 37 a[left] = temp; 38 } 39 } 40 } 41 } 复制代码 package com.sort; 2 3 //不稳定 4 public class 希尔排序 { 5 6 7 public static void main(String[] args) { 8 int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1}; 9 System.out.println("排序之前:"); 10 for (int i = 0; i < a.length; i++) { 11 System.out.print(a[i]+" "); 12 } 13 //希尔排序 14 int d = a.length; 15 while(true){ 16 d = d / 2; 17 for(int x=0;x<d;x++){ 18 for(int i=x+d;i<a.length;i=i+d){ 19 int temp = a[i]; 20 int j; 21 for(j=i-d;j>=0&&a[j]>temp;j=j-d){ 22 a[j+d] = a[j]; 23 } 24 a[j+d] = temp; 25 } 26 } 27 if(d == 1){ 28 break; 29 } 30 } 31 System.out.println(); 32 System.out.println("排序之后:"); 33 for (int i = 0; i < a.length; i++) { 34 System.out.print(a[i]+" "); 35 } 36 } 37 38 } 复制代码 |