标签:
排序算法一共有八种
具体每种算法:
直接插入排序:
public class DirectInsertSort { public static void main(String[] args){ Random random = new Random(); int a[] = new int[13]; for (int i = 0; i < a.length; i++) { a[i] = random.nextInt(100) + 1; } System.out.print("排序前:"); for(int i =0;i<a.length;i++){ System.out.print(a[i]+","); } System.out.println(); for(int i =1;i<a.length;i++){ //temp為待插的數 int temp =a[i]; //j為記錄下temp插入的位置 int j; for(j=i-1;j>=0;j--){ //每次將比temp大的數往后移一位 if(a[j]>temp){ a[j+1] = a[j]; } else{ //防止j往下走, break; } } a[j+1]=temp; } System.out.print("排序后:"); for(int k= 0;k<a.length;k++){ System.out.print(a[k]+","); } } }
二分插入排序:
希尔排序:
冒泡排序:
public class MaoPaoSort { public static void main(String[] args) { Random random = new Random(); int a[] = new int[13]; for (int i = 0; i < a.length; i++) { a[i] = random.nextInt(100) + 1; } System.out.print("排序前:"); for(int i =0;i<a.length;i++){ System.out.print(a[i]+","); } System.out.println(); for(int i =0;i<a.length;i++){ for(int j =0;j<a.length-1-i;j++){ int temp; if(a[j]>a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.print("排序后:"); for(int k= 0;k<a.length;k++){ System.out.print(a[k]+","); } } }
快速排序:
public class QuickSort { public static void main(String[] args) { Random random = new Random(); int a[] = new int[13]; for (int i = 0; i < a.length; i++) { a[i] = random.nextInt(100) + 1; } System.out.print("排序前:"); for(int i =0;i<a.length;i++){ System.out.print(a[i]+","); } quicksort(a, 0, a.length-1); System.out.println(); System.out.print("排序后:"); for(int k= 0;k<a.length;k++){ System.out.print(a[k]+","); } } private static void quicksort(int []num,int start,int end){ int i = start; int j = end; int base = num[i]; if(start>=end) return; while(i!=j){ while(num[j]>=base && j>i){ j--; } if(i<j){ num[i]=num[j]; //比忘了 i++; } while(num[i]<=base && i<j){ i++; } if(i<j){ num[j]=num[i]; //別忘了 j--; } } num[i]=base; quicksort(num,start,i-1); quicksort(num,i+1,end); } }
直接选择排序:
public class DirectSelectSort { public static void main(String[] args) { Random random = new Random(); int a[] = new int[13]; for (int i = 0; i < a.length; i++) { a[i] = random.nextInt(100) + 1; } System.out.print("排序前:"); for(int i =0;i<a.length;i++){ System.out.print(a[i]+","); } method(a); System.out.println(); System.out.print("排序后:"); for(int k= 0;k<a.length;k++){ System.out.print(a[k]+","); } } private static void method(int []num){ for(int i =0;i<num.length;i++){ int min = num[i]; int index= i; int temp;//用來交換的中間值 for(int j = i+1;j<num.length;j++){ if(num[j]<min){ min=num[j]; index=j; } } num[index]=num[i]; num[i]=min; } } }
堆排序:
归并排序:
标签:
原文地址:http://www.cnblogs.com/could-deng/p/5055433.html