Java珠算排序算法

珠算排序算法

珠算排序算法的介紹

詳情請看zhuSort2相關的代碼

 

/**
 * @author xiyou
 * @version 1.2
 * @date 2019/12/19 9:34
 */
public class ThreadSort {

    /**
     * 睡眠排序
     *
     * @param array
     */
    public static void sleepSort(int[] array) {
        for (int num : array) {
            new Thread(() -> {
                try {
                    Thread.sleep(num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(num);
            }).start();
        }
    }

    /**
     * 珠排序算法,但是有一個最大的問題就是:數組必須連續而且不能爲0和負數
     * 而且不能處理重複數據
     *
     * @param array
     * @return
     */
    public static int[] zhuSort(int[] array) {
        int len = array.length;
        int result[] = new int[len];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < array[i]; j++) {
                result[j] = result[j] + 1;
            }
        }
        return result;
    }

    /**
     * 珠排序算法完全版
     *
     * @param array
     * @return
     */
    public static int[] zhuSort2(int[] array) {
        int len = array.length;
        int max = 0;
        //求出數組裏面的最大值,其實也是珠最大的值
        for (int one : array) {
            max = Math.max(one, max);
        }
        //result[i]是落下後珠的每一列珠的高度
        int result[] = new int[max];
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < array[i]; j++) {
                result[j] = result[j] + 1;
            }
        }
        StringBuffer result3Str = new StringBuffer();
        for (int i : result) {
            result3Str.append(i + ",");
        }
        //result3Str就是衆多珠落下後組成的字符串數組
        System.out.println(result3Str.toString());

        int num = 0;
        int res[] = new int[len];
        //當前橫着的長度與下一個橫着的相減的值
        int high = 0;
        for (int i = 0; i < max - 1; i++) {
            high = result[i] - result[i + 1];
            if (high > 0) {
                res[num] = i + 1;
                num++;
                while (high > 1) {
                    res[num] = res[num - 1];
                    high--;
                    num++;
                }
            }


        }
        res[len - 1] = max;
        return res;
    }

    public static void main(String[] args) {
        int arr3[] = new int[]{6, 2, 4, 1, 2, 5, 9, 6, 6, 7, 23, 34, 54, 2};
//        sleepSort(arr);
        int result3[] = zhuSort2(arr3);
        StringBuffer result3Str = new StringBuffer();
        for (int i : result3) {
            result3Str.append(i + ",");
        }
        System.out.println(result3Str.toString());
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章