Java版冒泡排序法

package com.test;

/**
 * The bubble sorting demo in Java.
 * @author  Belin Wu
 * @version 1.0 2012-07-29
 */
public class BubbleSort {
	
	/**
	 * Sort the int array by bubble sorting.
	 * @param values the int array for sorting.
	 */
	public static void bubbleSort(int[] values) {
		boolean isOrdered = true; // 认为数组是有序的
		int temp = 0; // 数组元素交换时的临时变量
		
		// 进行数组排序
		for (int i = 0; i < values.length - 1; i++) {
			for (int j = 0; j < values.length - 1 - i; j++) {
				if (values[j] > values[j + 1]) {
					temp = values[j];
					values[j] = values[j + 1];
					values[j + 1] = temp;
					
					isOrdered = false; // 发生元素交换,数组是无序的。
				}
			}
			
			// 判断是否可以结束数组排序
			if (!isOrdered) {
				isOrdered = true; // 再次认为数组是有序的
			} else {
				break; // 跳出外层for循环
			}
		}
	}
	
	/**
	 * Test the bubble sorting.
	 * @param args the console arguments as a string array.
	 */
	public static void main(String[] args) {
		// 初始化数组
		int[] values = {1, -1, 3, 3, 2, 9, -10, 7, 6, 5};
		
		// 调用方法
		bubbleSort(values);
		
		// 打印数组
		for (int i = 0; i < values.length; i++) {
			System.out.println("values[" + i + "] = " + values[i]);
		}
		
		/* 输出结果
		values[0] = -10
		values[1] = -1
		values[2] = 1
		values[3] = 2
		values[4] = 3
		values[5] = 3
		values[6] = 5
		values[7] = 6
		values[8] = 7
		values[9] = 9
		*/
	}
}

转载于:https://my.oschina.net/belinwu/blog/69719

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值