一摞烙饼的排序

来源:互联网 发布:什么软件编辑dll 编辑:程序博客网 时间:2024/04/27 16:25

编程之美中的一道算法题目,原程序没看懂,自己按照书中思路用Java写的程序。

原题目:“我以前在餐馆打工,顾客经常点非常多的烙饼。店里的饼大小不一,我习惯在到达顾客饭桌之前,把一摞饼按照大小次序摆好——小的在上面,大的在下面。由于我一只手托着盘子,只好用另一只手,一次抓住最上面的几块饼,把他们上下颠倒个个儿,反复几次之后,这摞烙饼就排好序了。”

只是用自己想的最笨的方法把题目所需的过程大概完成了下。

public class bing {static int[] bin = { 1, 4, 5, 8, 10, 2, 3, 7, 2, 23, 37, 47, 38, 38, 17, 5,8, 10, 2, 3, 7, 2, 23, 37, 47, 87 };public static void main(String args[]) {int m = bin.length;int count = 0;for (int i = 0; i < bin.length; i++) {System.out.print(bin[i] + "   ");}System.out.println("初始數組順序");while (!Okay()) {if (Max(m - 1) == (m - 1)) {m--;continue;} else {swap(0, Max(m - 1));swap(0, m - 1);count += 2;m--;}for (int i = 0; i < bin.length; i++) {System.out.print(bin[i] + "   ");}System.out.println("第" + (count / 2) + "趟");}System.out.println("共需要翻转" + count + "次");}// 翻轉public static void swap(int m, int n) {if (m >= n)return;else {int temp = bin[m];bin[m] = bin[n];bin[n] = temp;swap(++m, --n);}}// 排好 truepublic static boolean Okay() {for (int i = 1; i < bin.length; i++) {if (bin[i - 1] > bin[i])return false;}return true;}// 得到数组前n位的最大值下标public static int Max(int n) {int max = 0;int index = 0;for (int i = 0; i <= n; i++) {if (max <= bin[i]) {max = bin[i];index = i;}}return index;}}


原创粉丝点击