Java实现的冒泡法、选择法和插入排序算法
import java.util.Arrays; /** * 排序算法 * */ public class SortDemo { public static void main(String[] args) { int[] ary = {3,1,4,9,2,5,6}; selectionSort(ary); System.out.println(Arrays.toString(ary)); bubbleSort(ary); System.out.println(Arrays.toString(ary)); insertionSort(ary); System.out.println(Arrays.toString(ary)); } /** 插入式排序 */ public static void insertionSort(int[] ary){ int i,j,k; for(i=1; i<ary.length; i++){ k = ary[i];//取出 //查找位置 for(j=i-1; j>=0 && k<ary[j]; j--){ ary[j+1]=ary[j];//向后移动元素 } ary[j+1]=k;//插入 } } /** 冒泡排序 */ public static void bubbleSort(int[] ary){ for(int i=0; i<ary.length-1; i++){ for(int j=0; j<ary.length-i-1; j++){ if(ary[j]>ary[j+1]){ int t=ary[j];ary[j]=ary[j+1];ary[j+1]=t; } } } } /** 选择排序: 每轮选择一个最小的放到前面 */ public static void selectionSort(int[] ary){ for(int i=0; i<ary.length-1; i++){ for(int j=i+1; j<ary.length; j++){ if(ary[i]>ary[j]){ int t=ary[i];ary[i]=ary[j];ary[j]=t; } } } } }