j2se学习笔记七
一个java程序员不仅能熟练的使用容器操作对象,而且要掌握基本的排序算法,最重要的8中排序,插入(直接插入,希尔),选择(简单选择,堆排),交换(冒泡,快排),归并,基数排序。
看过很多面试中很多时候考到冒泡排序,刚开始考虑的少,只会写个简单的排序,后来学到了更加有效率的改进方法,代码如下:
package csdream.sort.bubble; import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] a = { 12, 3, 25, 6, 7, 9, 14, 2, 31, 88, 48 }; System.out.println("方法bubbleSort输出的结果:"); bubbleSort(a); System.out.println("方法advancedBubbleSort输出的结果:"); advancedBubbleSort(a); System.out.println("方法advancedBubbleSort输出的结果:"); finalBubbleSort(a); } public static void bubbleSort(int[] a) { for (int j = a.length; j > 0; j--) { for (int i = 0; i < a.length - 1; i++) { int temp = 0; if (a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } System.out.println(Arrays.toString(a)); } public static void advancedBubbleSort(int[] a) { for (int j = a.length; j > 0; j--) { // 因为每次的遍历比较都会在数组末尾得到一个最大数,所以下次比较最后两位的比较没有必要! // 所以把内置的遍历比较范围改为i<a.length-1-j; for (int i = 0; i < a.length - 1 - j; i++) { int temp = 0; if (a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } System.out.println(Arrays.toString(a)); } public static void finalBubbleSort(int[] a) { //有些情况下经过很少次的交互后数组就会有序,则再进行遍历比较就会多余,所以加入boolean //来控制遍历比较趟数! for (int j = a.length; j > 0; j--) { boolean sorted = true;//假定开始有序 for (int i = 0; i < a.length - 1; i++) { int temp = 0; if (a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; sorted = false;//若无序则继续遍历比较 } } if(sorted) {//有序即跳出循环不在遍历比较 break; } } System.out.println(Arrays.toString(a)); } }
通过对冒泡排序的新的认识,觉得很简单的算法也有很多改进的地方,所以在以后的学习中一定要多思考多总结,这样才会学到程序的精髓!
芝兰生于幽林,不以无人而不芳;
君子修道立德,不以穷困而改节;

浙公网安备 33010602011771号