Demo entry 6641697

bubble sort

   

Submitted by cst on Sep 20, 2017 at 05:51
Language: Java. Code size: 913 Bytes.

public class Rank{
	public static void main(String[] args){
		int array[] = {6, 3, 8, 5, 4, 2, 9, 1, 7, 0};		//定义一个数组并赋值
		System.out.print("初始数组为:  ");
		for (int i = 0; i < array.length; i++){				//输出初始数组的值
			System.out.print(array[i] + " ");
		}
		System.out.println();
		for (int i = 1; i < array.length; i++){				//有(length - 1)个这样的元素
			for (int j = 0; j < array.length - i; j++){		//每趟需要的次数,随【i】的增加而减少
				if (array[j] > array[j+1]){                 //构建比较机制,使大的数向右边移动,
					int temp = array[j];					//直至它的右边没有比它大的数
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
			System.out.print("第" + i + "轮的结果:");		//每一轮的结果
			for (int j = 0; j < array.length; j++){
				System.out.print(" " + array[j]);
			}
			System.out.println();
		}
		System.out.print("排序后的结果:");
		for (int j = 0; j < array.length; j++){				//输出排序后的结果
			System.out.print(" " + array[j]);
		}		
	}
}

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).