标签:
public class ArraySort { public static void main(String[] args) { // TODO Auto-generated method stub int sortNumber = 5; int sortCountA = 0; int sortCountB = 0; int arraySourceA[] = {6, 3, 21, 43, 5667, 7890, 123, 4, 4323, 5453, 2323, 45245, 3213, 134143, 1234}; for ( int i = 0; i < arraySourceA.length; i++) { for (int j = i + 1; j < arraySourceA.length; j++){ if (arraySourceA[i] < arraySourceA[j]) { int temp; temp = arraySourceA[j]; arraySourceA[j] = arraySourceA[i]; arraySourceA[i] = temp; } sortCountA++; } sortCountA++; } int arraySourceB[] = {6, 3, 21, 43, 5667, 7890, 123, 4, 4323, 5453, 2323, 45245, 3213, 134143, 1234}; int[] arraySortB = new int[sortNumber]; for ( int i = 0; i < arraySourceB.length; i++) { if (i < sortNumber ) { arraySortB[i] = arraySourceB[i]; if (i == (sortNumber -1)){ for (int j = 0; j < arraySortB.length; j++) { for (int k = j + 1; k < arraySortB.length; k++) { if (arraySortB[j] < arraySortB[k]) { int temp; temp = arraySortB[k]; arraySortB[k] = arraySortB[j]; arraySortB[j] = temp; } sortCountB++; } sortCountB++; } } } else { if (arraySourceB[i] > arraySortB[sortNumber-1]) { arraySortB[sortNumber-1] = arraySourceB[i]; for (int j = 0; j < arraySortB.length; j++) { for (int k = j + 1; k < arraySortB.length; k++) { if (arraySortB[j] < arraySortB[k]) { int temp; temp = arraySortB[k]; arraySortB[k] = arraySortB[j]; arraySortB[j] = temp; } sortCountB++; } sortCountB++; } } } sortCountB++; } for (int i = 0; i < arraySortB.length; i++) { System.out.println(arraySortB[i]); } System.out.println("A sort count is: " + sortCountA); System.out.println("A result is:" + arraySourceA[sortNumber - 1]); System.out.println("B sort count is: " + sortCountB); System.out.println("B result is:" + arraySortB[sortNumber - 1]); } }
输出:
134143
45245
7890
5667
5453
A sort count is: 120
A result is:5453
B sort count is: 135
B result is:5453
十五个元素好像B算法没有效率一样,但如何将元素搞到29个呢?
134143
134143
45245
45245
7890
A sort count is: 435
A result is:7890
B sort count is: 209
B result is:7890
进一步,如何57个元素呢?是不是B算法越来越好了?
134143
134143
134143
134143
45245
A sort count is: 1653
A result is:45245
B sort count is: 282
B result is:45245
标签:
原文地址:http://www.cnblogs.com/aguncn/p/4496981.html