首页 > 编程 > Java > 正文

Java_常见排序算法整理

2019-11-06 06:02:57
字体:
来源:转载
供稿:网友
冒泡排序 对当前还未排好序的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。package javastudy.sort;public class BumbleSort { public static void main(String[] args) { int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1}; int n = arr.length; int temp = -1; for(int i = 0; i < n-1; i++) { for(int j = i + 1; j < n; j++) { if(arr[i] > arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } for(int i = 0; i < n; i++) System.out.PRintln(arr[i]); }}选择排序package javastudy.sort;public class SelectionSort { public static void main(String[] args) { int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1}; int n = arr.length; int select = -1; int temp = -1; for(int i = 0; i < n - 1; i++) { select = i; //记录最小值得下标 for(int j = i + 1; j < n; j++) { if(arr[select] > arr[j]) { select = j; } } if(select != i) { temp = arr[i]; arr[i] = arr[select]; arr[select] = temp; } } for(int i = 0; i < n; i++) System.out.println(arr[i]); }}二元选择排序package javastudy.sort;public class BinarySelectSort { public static void main(String[] args) { int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1}; int n = arr.length; int min, max, temp; for(int i = 0; i <= n/2; i++) { min = max = i; for(int j = i + 1; j < n - i; j++) { if(arr[min] > arr[j]) { min = j; continue; } if(arr[max] < arr[j]) max = j; } if(i != min) { temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } if(i != max) { temp = arr[n - i - 1];arr[n - i -1] = arr[max];arr[max] = temp; } } for(int i = 0; i < n; i++) { System.out.println(arr[i]); } }}插入排序package javastudy.sort;public class InsertSort { public static void main(String[] args) { int arr[] = new int[]{33, 22, 40, 10, 8, 15, 9, 18, 20, 1}; int n = arr.length; for (int i = 1; i < n; i++) { if (arr[i] < arr[i - 1]) { int valueToInsert = arr[i]; int j; for (j = i - 1; j >= 0 && valueToInsert < arr[j]; j--) { arr[j + 1] = arr[j]; } arr[j+1] = valueToInsert; } } for(int i = 0; i < n; i++) System.out.println(arr[i]); }}快速排序归并排序桶排序/基数排序(Radix Sort)
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表