Discuss / Java / 排序练习

排序练习

Topic source

YANGZY1202

#1 Created at ... [Delete] [Delete and Lock User]

import java.util.Arrays;

/**
 * 降序排序
 */
public class Main {
	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-1;i++) {
			for (int j=0;j<ns.length-1-i;j++) {
				if (ns[j] < ns[j+1]) {
					int t =ns[j];
					ns[j]=ns[j+1];
					ns[j+1]=t;
				}
			}
		}
				
		// 排序后:
		System.out.println(Arrays.toString(ns));
		if (Arrays.toString(ns).equals("[96, 89, 73, 65, 50, 36, 28, 18, 12, 8]")) {
			System.out.println("测试成功");
		} else {
			System.out.println("测试失败");
		}
	}
}

YANGZY1202

#2 Created at ... [Delete] [Delete and Lock User]

补充另外一种解法——先用Array.sort()正序排,然后直接将数组元素对调;

import java.util.Arrays;

/**
 * 降序排序(解法二)
 */
public class Main2 {
	public static void main(String[] args) {
		int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
		// 排序前:
		System.out.println(Arrays.toString(ns));
		
		// 排序:先用Array.sort()正序排,然后直接将数组元素对调;
		Arrays.sort(ns);
		for (int begin = 0, end = ns.length - 1; begin < end; begin++, end--) {
			int temp = ns[end];
			ns[end] = ns[begin];
			ns[begin] = temp;
		}

		// 排序后:
		System.out.println(Arrays.toString(ns));
		if (Arrays.toString(ns).equals("[96, 89, 73, 65, 50, 36, 28, 18, 12, 8]")) {
			System.out.println("测试成功");
		} else {
			System.out.println("测试失败");
		}
	}
}


  • 1

Reply