冒泡排序
冒泡排序是从相邻的元素之间比较一轮一轮将最大的数组逐渐移到数组最右边,总共需要n-1轮排序
冒泡排序主要过程如下:
冒泡排序的实现代码:
public class Sort { //交换元素函数 public void swap(int[] arrs, int i, int j) { int temp = arrs[i]; arrs[i] = arrs[j]; arrs[j] = temp; } @Test public int[] bubble_Sort(int[] arrs) { System.out.println("排序前数组:"); for (int i : arrs) { System.out.print(i + " "); } System.out.println(); for(int i = 0; i < arrs.length - 1; i++) { for(int j = 0; j < arrs.length -1 -i; j++) { if(arrs[j] > arrs[j+1]) { swap(arrs, j, j+1);//交换元素 } } //打印每一轮的排序结果 System.out.println("第" + (i+1) +"轮排序:"); for (int num : arrs) { System.out.print(num + " "); } System.out.println(); } System.out.println(); System.out.println("排序后的数组为:"); for(int num : arrs) { System.out.print(num + " "); } return arrs; } //冒泡排序改进 public int[] bubble_Sort2(int[] arrs) { System.out.println("排序前数组:"); for (int i : arrs) { System.out.print(i + " "); } System.out.println(); for(int i = 0; i < arrs.length - 1; i++) { //设置一个标志位如果排序中已将达到有序程序退出 boolean flag = true; for(int j = 0; j < arrs.length -1 -i; j++) { if(arrs[j] > arrs[j+1]) { swap(arrs, j, j+1);//交换元素 flag = false; } } if(flag) { //如果元素有序程序退出 break; } //打印每一轮的排序结果 System.out.println("第" + (i+1) +"轮排序:"); for (int num : arrs) { System.out.print(num + " "); } System.out.println(); } System.out.println(); System.out.println("排序后的数组为:"); for(int num : arrs) { System.out.print(num + " "); } return arrs; } }
public static void main(String[] args) { Sort sort = new Sort(); int[] arrs = {4,2,6,8,1,3,5}; sort.bubble_Sort1(arrs); }
public static void main(String[] args) { Sort sort = new Sort(); int[] arrs = {4,2,6,8,1,3,5}; sort.bubble_Sort2(arrs); }
突破昨天的自己