【学习笔记】
基础算法一:冒泡排序
冒泡排序实现类:
package sort;
/*** * @author jsyuger* 该类为冒泡排序算法* */
public class BubbleSort {//该方法为冒泡排序的public void bubble(int []arr) {int length = arr.length ; for(int i = 0 ; i < length - 1 ; i++) {for(int j = 1 ; j <= length - 1 ; j++) {if( i < j && arr[i] > arr[j]) { //交换条件很重要swapper(arr , i ,j);}}}}//数组交换两个数字的值public void swapper(int []arr , int i , int j) {int temp = arr[i];arr[i] = arr[j];arr[j] = temp ;}}
冒泡排序单元测试类:
package test;import org.junit.Test;import sort.BubbleSort;
/*** 排序算法的单元测试*/
public class TestSort {private int []array = { 5 , 12 , 34 , 6 , 0 , 7 , 22 , 8 , 16 };/*** 冒泡排序单元测试*/@Testpublic void testBubble() {BubbleSort bubbleSort = new BubbleSort();System.out.print("排序前: ");printArray(array);bubbleSort.bubble(array);System.out.print("排序后: ");printArray(array);}/*** 打印数组的公共方法* @param arr*/public void printArray(int []arr) { for(int a = 0 ; a <= arr.length - 1 ;a++)System.out.print(arr[a] + " ");System.out.println();}}