常见排序算法(java实现)
2015-07-26 14:25
746 查看
常见排序算法介绍
冒泡排序
代码:public class BubbleSort { public static void sort(int[] array) { int tValue; for (int i = 0; i < array.length; i++) { for (int j = i; j < array.length; j++) { if (array[i] > array[j]) { tValue = array[i]; array[i] = array[j]; array[j] = tValue; } } } } public static void main(String[] args) { int a[] = { 6, 2, 4, 5, 1, 9, 10, 7 }; sort(a); for (int v : a) { System.out.print(v + " "); } } }
输入结果:
1 2 4 5 6 7 9 10
插入排序:
效果图:代码:
public class InsertSort { public static void sort(int[] array) { int tValue; int j; for (int i = 0; i < array.length; i++) { j = i; tValue = array[i]; while (j > 0 && tValue < array[j - 1]) { array[j] = array[j - 1]; j--; } array[j] = tValue; } } public static void main(String[] args) { int a[] = { 6, 2, 4, 5, 1, 9, 10, 7 }; sort(a); for (int v : a) { System.out.print(v + " "); } } }
输入结果:
1 2 4 5 6 7 9 10
选择排序:
代码:public class SelectSort { public static void sort(int[] array) { int index, tValue; for (int i = 0; i < array.length; i++) { index = i; for (int j = i + 1; j < array.length; j++) { if (array[j] < array[index]) { index = j; } } if (index != i) { tValue = array[i]; array[i] = array[index]; array[index] = tValue; } } } public static void main(String[] args) { int a[] = { 6, 2, 4, 5, 1, 9, 10, 7 }; sort(a); for (int v : a) { System.out.print(v + " "); } } }
输入结果:
1 2 4 5 6 7 9 10
快速排序:
代码:public class QuickSort { public static void quickSort(int[] array, int left, int right) { int i, j, bValue, tValue; if (left > right) { return; } i = left; j = right; bValue = array[left]; while (i != j) { while (array[j] >= bValue && i < j) { j--; } while (array[i] <= bValue && i < j) { i++; } if (i < j) { tValue = array[i]; array[i] = array[j]; array[j] = tValue; } } array[left] = array[i]; array[i] = bValue; quickSort(array, left, i - 1); quickSort(array, i + 1, right); } public static void main(String[] args) { int a[] = { 6, 2, 4, 5, 1, 9, 10, 7 }; quickSort(a, 0, a.length - 1); for (int v : a) { System.out.print(v + " "); } } }
输入结果:
1 2 4 5 6 7 9 10
参考资料:
http://blog.jobbole.com/11745/相关文章推荐
- JAVA集中中 List Set Map 区别和关系
- eclipse编辑器下显示文件路径
- 开源 自由 java CMS - FreeCMS1.8 网上申报
- Java Base64、AES、SHA1、MD5加密算法
- JAVA注解
- [转]STRUTS2中的OGNL
- [LeetCOde][Java] Best Time to Buy and Sell Stock III
- [LeetCode][Java] Best Time to Buy and Sell Stock IV
- Struts2-02
- java:用UDP协议,开发一个聊天工具代码
- springmvc+mybatis+mysql整合实战
- eclipse修改java代码后报错: java.lang.OutOfMemoryError: PermGen space
- 学习java编程能往哪些方向发展
- Java关键字this、super使用总结
- jdk 安装
- 为什么要重写hashcode() 方法
- java中,随机的得到10个布尔类型的值,然后统计这些值出现的次数并输出!
- Java内部类学习笔记
- JAVA之四种线程池
- 深入浅出RxJava三–响应式的好处