public class Insert { public static void main(String[] args) { Random rand = new Random(100); int[] a = new int[rand.nextInt(50)]; int i, key, j; for ( i = 0; i < a.length; i++) a[i] = rand.nextInt(300); System.out.println(Arrays.toString(a)); for (j = 1; j < a.length; j++) { key = a[j]; i = j; while ( i >0 && a[i-1] >= key) { a[i] = a[i-1]; i--; } a[i] = key; } System.out.println(Arrays.toString(a)); } } or
public class Insert { public static void main(String[] args) { Random rand = new Random(100); int[] a = new int[rand.nextInt(50)]; int i, key, j; for ( i = 0; i < a.length; i++) a[i] = rand.nextInt(300); System.out.println(Arrays.toString(a)); for (j = 1; j < a.length; j++) { key = a[j]; i = j-1; while ( i >0 && a[i] >= key) { a[i+1] = a[i]; i--; } a[i+1] = key; } System.out.println(Arrays.toString(a)); } }
插入排序的效率:O(n*n);在随机数的情况下,比冒泡,选择快;在基本有序的数组中,插入排序几乎只需O(n);逆序的情况下,并不比冒泡快。
public class megerSort { public static void main(String[] args) { Random rand = new Random(46); int[] a = new int[rand.nextInt(20)]; for (int i = 0; i < a.length; i++) a[i] = rand.nextInt(100); System.out.print(Arrays.toString(a)); mergesort(a, 0, a.length - 1); System.out.println(); System.out.print(Arrays.toString(a)); } public static void mergesort(int[] a, int left, int right) { if (left < right) { int mid = (left + right) / 2; mergesort(a, left, mid); mergesort(a, mid + 1, right); merge(a, left, mid, right); } } public static void merge(int[] a, int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int[] b = new int[n1 + 2]; int[] c = new int[n2 + 2]; for (int i = 1; i < n1 + 1; i++) b[i] = a[l + i - 1]; for (int j = 1; j < n2 + 1; j++) c[j] = a[j + m]; b[n1 + 1] = 200; c[n2 + 1] = 200; int i = 1; int j = 1; for (int k = l; k <= r; k++) { if (b[i] < c[j]) { a[k] = b[i]; i++; } else { a[k] = c[j]; j++; } } } }
public class quicksort { public static void main(String[] args) { int[] a=new int[(int)(Math.random()*200)]; for (int i = 0; i < a.length; i++) a[i] = (int) (Math.random()*1000); System.out.print(Arrays.toString(a)); quicksort(a,0,a.length-1); System.out.println(); System.out.print(Arrays.toString(a)); } public static void quicksort(int[] a,int low,int high) { if(low<high){ int mid = partition(a,low,high); quicksort(a,low,mid-1); quicksort(a,mid+1,high); } } public static int partition(int[] a, int low, int high) { int k = a[high]; int t , j = low-1; for (int i = low; i < high; i++) { if(k > a[i]){ j++; t = a[i]; a[i] = a[j]; a[j] = t; } } t = a[j+1]; a[j+1] = k; a[high] = t; return j+1; } }
插入、归并、快速排序
最新推荐文章于 2024-03-28 00:29:10 发布