漫畫:三種 “奇葩” 的排序演算法程式碼實現
阿新 • • 發佈:2019-12-02
1: 睡眠排序
public class Main2 { public static void sleepSort(int[] array) { for (int i : array) { new Thread(()->{ try { Thread.sleep(i); } catch (Exception e) { e.printStackTrace(); } System.out.println(i); }).start(); } } public static void main(String[] args) { int[] array = { 10, 30, 50, 60, 100, 40, 150, 200, 70 }; sleepSort(array); } }
2:猴子排序
package app; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class randSort{ public static void randSortX(int [] array){ List<Integer> list=new ArrayList<>(); for (Integer integer : array) { list.add(integer); } int pre=0; int index=0; while(true){ pre=0; for (index = 1; index < list.size(); index++) { if(list.get(index)>list.get(pre)){ pre++; }else{ break; } } if(pre+1==list.size()){ break; } Collections.shuffle(list); } System.out.println(list.toString()); } public static void main(String[] args) { int[] array = { 10, 30, 50, 60, 100, 40, 150, 200, 70 }; randSortX(array); } }
3:3.珠排序
package app; public class beadSort{ /** * 這裡二維陣列 由待排序陣列中最大值確定 */ public static void beadSortX(int[] array) { int MAXLEN=0; for (int i : array) { MAXLEN=Math.max(MAXLEN, i); } int [][] matrix=new int[MAXLEN][MAXLEN]; int k=0; for (int i : array) { for (int j = 0; j < i; j++) { matrix[k][j]=1; } ++k; } for (int i = matrix.length-1; i>0; i--) { for (int j = 0; j < matrix.length; j++) { if(matrix[i][j]==0){ int m=i; for (int z = i; z >=0; z--) { if(matrix[z][j]==1){ matrix[m--][j]=1; matrix[z][j]=0; } } } } } for (int i = 0; i < MAXLEN; i++) { int sum=0; for (int j = 0; j < MAXLEN; j++) { if(matrix[i][j]!=0){ sum++; } } if(sum!=0){ System.out.print(sum+ " "); } } } public static void main(String[] args) { int[] array = { 10, 30, 50, 60, 100, 40, 150, 200, 70 }; int[] x = { 3,2,4,5,1}; beadSortX(array); } }
&n