冒泡: 其实就是把一个数组里的数据颠倒一下
1 public static String[] loopRank(String[] bookIDs, int num) 2 { 3 if (null != bookIDs && 0 != bookIDs.length) 4 { 5 if (num >= bookIDs.length) 6 { 7 num = 1; 8 } 9 10 int length = bookIDs.length; 11 String[] temp = new String[length]; 12 System.arraycopy(bookIDs, length - num, temp, 0, num); //源数组、源数组要复制的起始位置、目标数组、目标数组要复制的起始位置、要复制的长度 13 System.arraycopy(bookIDs, 0, temp, num, length - num); 14 return temp; 15 } 16 else 17 { 18 return bookIDs; 19 } 20 }
随机:
public static String[] randomRank(String[] bookIDs, int num) { if (null != bookIDs && 0 != bookIDs.length) { if (num >= bookIDs.length) { num = bookIDs.length; } ArrayList list = new ArrayList(bookIDs.length); for (int ran = 0; ran < bookIDs.length; ++ran) { list.add(bookIDs[ran]); } int[] arg6 = randon(num, bookIDs.length); ArrayList reList = new ArrayList(bookIDs.length); int ids; for (ids = 0; ids < arg6.length; ++ids) { String o = (String) list.get(arg6[ids]); reList.add(o); } for (ids = 0; ids < reList.size(); ++ids) { list.remove(reList.get(ids)); } reList.addAll(list); String[] arg7 = new String[reList.size()]; return (String[]) ((String[]) reList.toArray(arg7)); } else { return null; } }
1 private static int[] randon(int num, int length) { 2 boolean[] cards = new boolean[length]; 3 4 for (int r = 0; r < length; ++r) { 5 cards[r] = false; 6 } 7 8 Random arg6 = new Random(); 9 int[] result = new int[num]; 10 11 for (int index = 0; index < num; ++index) { 12 int x; 13 do { 14 x = arg6.nextInt(length); 15 } while (cards[x]); 16 17 cards[x] = true; 18 result[index] = x; 19 } 20 21 return result; 22 }