Demo entry 6780757

冒泡排序

   

Submitted by anonymous on Dec 28, 2018 at 16:18
Language: Java. Code size: 1.1 kB.

//BubbleSort.java
import java.util.ArrayList;
import java.util.Scanner;
/*
 * 冒泡排序
 */
public class BubbleSort {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		ArrayList<Integer> List = new ArrayList<Integer>();
		ArrayList<Integer> temp = new ArrayList<Integer>();
		int number = 0;
		System.out.print("Please input numbers and end with '999':");
		number=sc.nextInt();
		while(number!=999){
			List.add(number);
			number=sc.nextInt();
		}
		System.out.println("The original array:");
		for(int i=0;i<List.size();i++)
			System.out.print((int)List.get(i)+" ");
		for(int i=0;i<List.size();i++){//外层循环控制排序趟数
			for(int j=0;j<List.size()-1-i;j++){//内层循环控制每一趟排序多少次
				if((List.get(j) > List.get(j+1))){
					temp.add(List.get(j));
					//temp.remove(j);
					List.set(j, List.get(j+1));
					//temp.remove(j+1);
					List.set(j+1, temp.get(0));
					temp.remove(0);
				}
			} 		
		}
		System.out.println("\nSorted array:");
		for(int i=0;i<List.size();i++)
			System.out.print((int)List.get(i)+" ");
	}
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).