排序算法温习 - 冒泡排序

来源:互联网 发布:小仙女的网络意思 编辑:程序博客网 时间:2024/05/01 11:23
package com.plumage.datastructure;import org.junit.Test;/** * @author 羽毛 * 排序工具类 */public class SortUtils {/** * 冒泡排序算法 * @param arrays */public static void bubbleSort(int[] arrays) {//n个数据比较n-1次for(int i = 0; i < arrays.length - 1; i++) {for(int j = arrays.length - 1; j > i; j--) {//数组由小到大进行排序if(arrays[j] < arrays[j - 1]) {swap(arrays, j, j -1);}}}}/** * 将整型数组两个索引位置对应的值互换 * @param arrays * @param i * @param j */public static void swap(int[] arrays, int i, int j) {int temp;temp = arrays[i];arrays[i] = arrays[j];arrays[j] = temp;}/** * 遍历数组 * @param arrays */public static void print(int[] arrays) {System.out.print("排序后的数组元素为 :");for(int i = 0; i < arrays.length; i++) {if(arrays.length - 1 == i) {System.out.print(arrays[i]);}else {System.out.print(arrays[i] + ",");}}}@Testpublic void test() {int[] testArray = new int[]{7,31,74,39,12,41,83,96,100,20};bubbleSort(testArray);print(testArray);}}

原创粉丝点击