最近在看vamei君的
纸上谈兵: 排序算法简介及其C实现
一直对算法这块理解不好,所以跟着vamei君写一写,vamei君的博客也是非常赞,也在此表示感谢~
1 package com.sort; 2 3 /** 4 * java实现几种排序 5 * @author quxiaozha 6 * 7 */ 8 9 10 public class MySort { 11 //插入排序 12 public static int[] insert_sort(int[] a){ 13 int i,j; 14 // long start,end; 15 // start=System.nanoTime(); 16 for(j = 1; j < a.length; j++){ 17 i = j-1; 18 while((i>=0)&&(a[i+1]<a[i])){ 19 swap(a, i+1, i); 20 i--; 21 } 22 } 23 // end=System.nanoTime(); 24 // System.out.println("排序使用时间:"+(end-start)+" ns"); 25 return a; 26 27 } 28 29 //冒泡排序 30 public static int[] bubble_sort(int[] a){ 31 int i,j; 32 int sign; 33 for(j=0; j<a.length-1; j++){ 34 sign = 0; 35 for(i = a.length-1; i>j; i--){ 36 if(a[i-1] > a[i]){ 37 sign = 1; 38 swap(a, i-1, i); 39 } 40 } 41 if(sign == 0){ 42 break; 43 } 44 } 45 return a; 46 } 47 48 49 public static void printArray(int[] array) { 50 for (int i = 0; i < array.length; i++) { 51 System.out.print(array[i]); 52 if (i != array.length - 1) { 53 System.out.print(","); 54 } 55 } 56 System.out.println(); 57 } 58 59 public static int[] swap(int[] a, int from, int to){ 60 // System.out.println(from+"&&&&"+to); 61 if(from<0||from>a.length-1||to<0||to>a.length-1||from == to){ 62 Exception e = new Exception("数据下标越界"); 63 try { 64 throw e; 65 } catch (Exception e1) { 66 e1.printStackTrace(); 67 } 68 } 69 int temp = a[from]; 70 a[from] = a[to]; 71 a[to] = temp; 72 return a; 73 } 74 75 public static void main(String[] args){ 76 int[] a={49,38,65,97,76,13,27,49,78,34,12,64,1}; 77 // int[] a={49,38,65}; 78 System.out.println("排序前的数组:"); 79 printArray(a); 80 81 System.out.println("插入排序后的数组:"); 82 printArray(insert_sort(a.clone())); 83 84 System.out.println("冒泡排序后的数组:"); 85 printArray(bubble_sort(a.clone())); 86 87 } 88 }