Discuss / Java / 冒泡比较好理解的写法

冒泡比较好理解的写法

Topic source

simple

#1 Created at ... [Delete] [Delete and Lock User]
//升序
import java.util.Arrays;

public class Hello {
	public static void main(String[] args) {
		int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
		System.out.println(Arrays.toString(ns));
		for (int i = 0; i < ns.length; i++) {
			for (int j = i; j < ns.length; j++) {
				if (ns[j] < ns[i]) {
					int tmp = ns[i];
					ns[i] = ns[j];
					ns[j] = tmp;
				}
			}
		}
		System.out.println(Arrays.toString(ns));
	}
}


//降序
import java.util.Arrays;

public class Hello {
	public static void main(String[] args) {
		int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
		System.out.println(Arrays.toString(ns));
		for (int i = 0; i < ns.length; i++) {
			for (int j = i; j < ns.length; j++) {
				if (ns[j] > ns[i]) {
					int tmp = ns[i];
					ns[i] = ns[j];
					ns[j] = tmp;
				}
			}
		}
		System.out.println(Arrays.toString(ns));
	}
}




  • 1

Reply