import java.util.Arrays; /** * Created by Admin on 2018/3/31. */ public class Sort { public static void main(String[] args) { int a[] = {3,1,5,7,2,4,9,6,10,8}; System.out.println("排序后:"+ Arrays.toString(bubbleSort(a))); System.out.println("排序后:"+ Arrays.toString(selectSort(a))); System.out.println("排序后:"+ Arrays.toString(insertSort(a))); System.out.println("排序后:"+ Arrays.toString(quickSort(a,0, a.length - 1))); } public static int[] bubbleSort(int a[]) { int temp; for(int i=0;i<a.length;i++) { for(int j=0;j<a.length-i-1;j++) { if(a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } return a; } public static int[] selectSort(int[] a) { int length = a.length; for(int i=0;i<length;i++) { int key = a[i]; int position = i; for (int j=i+1;j<length;j++) { if(a[j]<key) { key = a[j]; position = j; } a[position] = a[j]; a[i]=key; } } return a; } public static int[] insertSort(int[] a) { for(int i=1;i<a.length;i++){//从头部第一个当做已经排好序的,把后面的一个一个的插到已经排好的列表中去。 int j; int x=a[i];//x为待插入元素 for(j=i;j>0 && x<a[j-1];j--){// 从已经排序的序列最右边的开始比较,找到比其小的数 a[j]=a[j-1]; } a[j]=x;//插入 } return a; } public static int[] quickSort(int[] a, int start, int end) { if (start < end) { int base = a[start]; // 选定的基准值(第一个数值作为基准值) int temp; // 记录临时中间值 int i = start, j = end; do { while ((a[i] < base) && (i < end)) i++; while ((a[j] > base) && (j > start)) j--; if (i <= j) { temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } } while (i <= j); if (start < j) quickSort(a, start, j); if (end > i) quickSort(a, i, end); } return a; } }
java四种常用排序冒泡排序选择排序插入排序快速排序
猜你喜欢
转载自blog.csdn.net/ccmedu/article/details/79771076
今日推荐
周排行