java实现冒泡排序算法

  在数据结构中,冒泡排序算法算是比较简单和经典的排序算法了,算法基本思想:

1.比较相邻的两个数。如果第一个比第二个大,则交换这两个数的值,依次类推;

2.算法中有两个循环,每一次子循环完成时,都把最大的那个数放到最右边,直到循环结束,排序完成。

下面上算法代码:

package dataStructures;

import java.util.Scanner;

/** 
 * 类说明 
 * @author jiang
 * @date 创建时间:2014年10月6日 上午9:27:38 
 */
public class BubbleSort {

	//实现冒泡排序算法,输入整数数组,然后通过冒泡排序,从小到大的顺序输出
	//如:请输入一个整数数组(整数之间用空格隔开):
	//输入:20 25 658 56 58 54 68 
	//输出:20 25 54 56 58 68 658
	public void bubblesort(int str[]){
		for (int i = 0; i < str.length; i++) {
			for (int j = 0; j < str.length-1; j++) {  //这里注意j的最大值,由于有j+1,为了避免数组索引越界,所以最大值是str.length-2
				int temp = 0;
				if (str[j]>str[j+1]) {  //每一次循环都把最大的那个数放到最右边
					temp = str[j];
					str[j] = str[j+1];
					str[j+1] = temp;
				}
			}
		}
	}
	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);  //初始化输入流
		System.out.println("请输入一个整数数组:");
		String s1 = scanner.nextLine();
		String[] s2 = s1.split(" ");
		int[] str = new int[s2.length];
		for (int i = 0; i < str.length; i++) {
			str[i] = Integer.valueOf(s2[i]);       //将输入的字符型转化为整型的数组
		}
		BubbleSort bubbleSort = new BubbleSort();
		bubbleSort.bubblesort(str); 			  //数组排序
		System.out.println("排序后的数组:");
		for (int i = 0; i < str.length; i++) {
			System.out.print(str[i]+" ");         //输出
			
		}
		scanner.close();
	}
}
程序运行结果:

请输入一个整数数组:
25 25 35 658 45 5 6 9 8 42 35
排序后的数组:
5 6 8 9 25 25 35 35 42 45 658 

当然提到算法,就会有算法的时间复杂度和空间复杂度:

时间复杂度:o(n^2)

空间复杂度:o(1)

稳定性:稳定

你可能感兴趣的:(java,冒泡排序)