加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

排序算法总结

发布时间:2020-12-13 20:42:37 所属栏目:PHP教程 来源:网络整理
导读:代码写久了,越发的觉得写到后来回归的都是基
代码写久了,越发的觉得写到后来回归的都是基础。顿时觉得后悔大1大2没好好学这些计算机基础课程,亏大了。
总结下排序算法:
package 排序算法; /** * 1.选择排序 * 2.插入排序 * 3.归并排序 * 4.快速排序 * * @author Administrator * */ public class 4种排序算法 { public static void main(String[] args) { int[] arr = { 2,5,6,7,4,3,1,3 }; // selectSort(arr); // insertedSort(arr); // mergeSort(arr,arr.length - 1); quickSort(arr,arr.length - 1); out(arr); } // 输出 public static void out(int[] arr) { for (int e : arr) System.out.print(e + ","); } // 1.选择排序 public static void selectSort(int[] a) { for (int i = 0; i < a.length; i++) for (int j = i + 1; j < a.length; j++) { int key = a[i]; if (key > a[j]) { a[i] = a[j]; a[j] = key; } } } // 2.插入排序 public static void insertedSort(int[] a) { for (int i = 1; i < a.length; i++) { int key = a[i]; int j = i - 1; while (j >= 0 && key < a[j]) { a[j + 1] = a[j]; a[j] = key; j--; } } } // 3.归并排序(分治法) public static void mergeSort(int[] a,int low,int high) { if (low < high) { int mid = (low + high) / 2; // 递归到最小原子 mergeSort(a,low,mid); mergeSort(a,mid + 1,high); // 合并数组 mergeArray(a,mid,high); } } // 合并数组 private static void mergeArray(int[] a,int mid,int high) { int N = high - low; int[] temp = new int[N + 1]; int i = low,j = mid + 1; int m = mid,n = high; int k = 0; while (i <= m && j <= n) temp[k++] = (a[i] < a[j] ? a[i++] : a[j++]); while (i <= m) temp[k++] = a[i++]; while (j <= n) temp[k++] = a[j++]; for (i = 0; i < k; i++) a[low + i] = temp[i]; } // 4.快速排序(分治法) public static void quickSort(int[] a,int high) { if (low < high) { int r = adjustArray(a,high); quickSort(a,r - 1); quickSort(a,r + 1,high); } } // 提取数组中的首个元素,分割。小的元素放在<strong>标志</strong>的左侧,比 // 标志大的元素放在其右侧,最后返回标志元素的位置 private static int adjustArray(int[] a,int high) { int i = low,j = high; int spcValue = a[low]; while (i < j) { while (a[j] >= spcValue && i < j) j--; if (a[j] < spcValue) a[i++] = a[j]; while (a[i] <= spcValue && i < j) i++; if (a[i] > spcValue) a[j--] = a[i]; } a[i] = spcValue; return i; } }


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读