排序算法温习 - 冒泡排序

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] + ",");
			}
		}
	}
	
	@Test
	public void test() {
		int[] testArray = new int[]{7,31,74,39,12,41,83,96,100,20};
		bubbleSort(testArray);
		print(testArray);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值