您的位置:首页 > 其它

冒泡排序

2017-09-14 11:23 239 查看
/**
* Project Name:Algorithm
* File Name:BubbleSort.java
* Package Name:
* Date:2017年9月14日上午10:15:36
* Copyright (c) 2017, chenzhou1025@126.com All Rights Reserved.
*
*/

/**
* ClassName:BubbleSort
* Function: 冒泡排序.
* Reason:     代码实现冒泡排序算法. 测试数据集:6 3 5 7 0 4 12
* Analysis: 若记录序列的初始状态为"正序",则冒泡排序过程只需进行一趟排序,在排序过程中只需进行n-1次比较,且不移动记录;
*             反之,若记录序列的初始状态为"逆序",则需进行n(n-1)/2次比较和记录移动。
*             因此冒泡排序总的时间复杂度为O(n*n)。
* Date:     2017年9月14日 上午10:15:36
* @author   michael
* @version
* @since    JDK 1.7
* @see
*/
public class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = "";
while (sc.hasNext()) {
input = sc.nextLine();
System.out.println("输入值:" + input);
long startTime = System.currentTimeMillis();
String[] str = input.split(" ");
int[] arr = new int[str.length];
// 字符串数组转化成int数组
for (int i = 0; i < str.length; i++) {
arr[i] = Integer.parseInt(str[i]);
}
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1; j++) {
int temp;
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println();
System.out.print("第" + (i + 1) + "次循环结果:");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j]);
}
}
long endTime = System.currentTimeMillis();
System.out.println();
System.out.println();
System.out.println("最终排序结果:");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j]);
}
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: