/** * 設有n我的依圍成一圈,從第1我的開始報數,數到第m我的出列,而後從 * 出列的下一我的開始報數,數到第m我的又出列,…,如此反覆到全部的人所有出列爲 * 止。設n我的的編號分別爲1,2,…,n,打印出出列的順序;要求用java 實現。 */ @org.junit.Test public void test3() { //初始化整個隊伍 int[] peos = new int[9]; for (int i = 1; i < peos.length+1; i++) { peos[i-1] = i; } System.out.println(Arrays.toString(peos)); //出隊步長 int m = 2; //出隊記錄 int[] out = new int[9]; int n = 0; for (int i = 0; peos.length != 0; i++) { //每次出隊時,當前序號。 n = m + n - 1; while (n >= peos.length) { // 若是n下標超過數組長度,就從頭開始再算。 n = n - peos.length; } out[i] = peos[n]; /* * 將數組n項後面的元素所有前移一項。能夠替換爲System.arraycopy方法。 * System.arraycopy(peos, n + 1, peos, n, peos.length - 1 - n);
* 生成出隊後的新數組 */ for (int j = n; j < peos.length - 1; j++) { peos[j] = peos[j + 1]; } peos = Arrays.copyOf(peos, peos.length - 1); } System.out.println(Arrays.toString(out)); }
/** * 插入排序原理參照撲克牌,每一次取出一張牌,設爲Ai ,插入到應該在的順序裏,並不須要新建一個新的數組。 * 從數組第二個元素開始,將Ai 與前面的元素(已經排序的i個元素)比較, * 若是是升序,則應該找到Ai首次遇到大於本身的元素的位置,設爲j,Ai排序本次循環後應該位於j處, * 而從j到i-1的全部元素向後移動一位,填補原先Ai(i)的地方,Ai的值插入到移位後空出來的j(處) * 這樣實現了從i處抽取一個牌,插入到準確的位置。依次循環這個過程,循環到的每個元素最後都會插入到它應該所處的位置上,從而實現了排序。 * [1, 2, 4, 5, 6, 7, 9, 3, 8] * [1, 2, 3, 4, 5, 6, 7, 9, 8] * @param array * @param up */ public static void insertSort(int[] array ,boolean up){ for(int i=1;i<array.length;i++){ int current = array[i]; int from=0,to=i-1; for(int j=from;j<=to;j++){ if(current <= array[j]){ for(int n=to;n>=j;n--){ array[n+1] = array[n]; } array[j] = current; break; } } System.out.println(Arrays.toString(array)); } }
/** * 冒泡排序 * 選擇第一個元素,依次與後面的元素比較,若是大於後面的元素就交換,一輪下來,保證最大的元素放在最後面。 * 循環這個過程 */ public static void maoPaoSort(int[] array ,boolean up){ if(up){ for(int j = 0;j<array.length-1;j++){ int current = array[0]; for(int i=0;i< array.length-j-1;i++){ if(current> array[i+1]){ array[i]= array[i+1]; array[i+1]=current; }else if(current< array[i+1]){ current = array[i+1]; } } } }else{ for(int j = 0;j<array.length-1;j++){ int current = array[0]; for(int i=0;i< array.length-j-1;i++){ if(current < array[i+1]){ array[i]= array[i+1]; array[i+1]=current; }else if(current > array[i+1]){ current = array[i+1]; } } } } System.out.println(Arrays.toString(array)); }