分治算法 ———— 排序问题
来源:互联网 发布:8888端口干嘛的 编辑:程序博客网 时间:2024/06/07 23:05
使用分制算法来解决排序问题,是一种比较高效的方法。
这里是原理图
在java中的代码是这样的,先看排序的代码,然后再看主函数
package com.li;public class MergeSort { public static void sort (double[] a, int begin, int end) { if((end - begin) >= 1) { int splitPoint = split(begin, end); sort(a, begin, splitPoint); sort(a, splitPoint + 1, end); join(a, begin, splitPoint, end); } } private static int split(int begin, int end) { return ((begin + end) / 2); } private static void join(double[] a, int begin, int splitPoint, int end) { double[] temp; int intervalSize = (end - begin) + 1; temp = new double[intervalSize]; int nextLeft = begin; int nextRight = splitPoint + 1; int i = 0; while((nextLeft <= splitPoint) && (nextRight <= end)) { if(a[nextLeft] < a[nextRight]) { temp[i] = a[nextLeft]; i++; nextLeft++; } else { temp[i] = a[nextRight]; i++; nextRight++; } } while(nextLeft <= splitPoint) { temp[i] = a[nextLeft]; i++; nextLeft++; } while(nextRight <= end) { temp[i] = a[nextRight]; i++; nextRight++; } for(i=0; i<intervalSize; i++) { a[begin+i] = temp[i]; } }}
这是主函数
package com.li;public class MergeSortDemo { public static void main(String[] args) { // TODO 自动生成的方法存根 double[] b = {7.7, 5.5, 11, 3, 16, 4.4, 20, 14, 13, 42}; System.out.println("Before sorting"); int i; for(i=0; i<b.length; i++) { System.out.print(b[i] + " "); } System.out.println(); MergeSort.sort(b, 0, b.length-1); System.out.println("After sortint"); for(i=0; i<b.length; i++) { System.out.print(b[i] + " "); } }}
代码是依照图片中的样式进行编写的。
就是对一个数组进行划分,不停的细分,把复杂问题简单化,进而解决问题。
0 0
- 分治算法—合并排序
- 分治算法 ———— 排序问题
- 分治算法——快速排序
- 分治法算法——归并排序
- 分治算法——快速排序
- 分治算法—对数组排序
- 分治算法——快速排序,归并排序
- 分治算法——归并排序与快速排序
- 算法——分治算法
- 基础算法 —— 合并排序(分治法)
- 算法代码(2)——分治法排序
- 0004算法笔记——【分治法】合并排序
- 0005算法笔记——【分治法】快速排序
- 0004算法笔记——【分治法】合并排序
- 0005算法笔记——【分治法】快速排序
- 算法09:快速排序——分治法Part5
- 04算法笔记——【分治法】合并排序
- 分治归并排序算法——Java实现
- ZJNU 1903 Why Did the Cow Cross the Road III 树状数组
- 编程之美--2.4 1的数目之扩展问题
- Andrew NG机器学习课程笔记系列之——机器学习之逻辑回归(Logistic Regression)
- rtmp握手过程
- JPA主键生成器和主键生成策略
- 分治算法 ———— 排序问题
- MFC中利用FindFile函数在文件夹路径下连续读取多个文件
- java 7新特性-TWR(Try-with-resources)
- AJAX 初步学习(1)
- linux环境Mysql 5.7.13安装教程
- 计算机视觉和模式识别(一)
- 萌萌哒的第一题
- Qt实战开发-CSDN登陆界面布局
- 理解长短期记忆网络(LSTM NetWorks)