从抽牌游戏看到的知识
从二分排序看到的知识
大家都知道计算机排序有很多种,比如冒泡排序、快速排序、选择排序、希尔排序等,这么多排序方法,你真正掌握的到底有几个,每个人会根据自己对知识的掌握程度以及需求选择适合自己项目需求的排序方式。现在我想说的是二分治算法,可能大家都很熟悉或者在网上找到例子。你这样说的话,我 就不敢接受你的观点了。接下来我用实际的例子引导你的思想观念,看看你自己对二分治掌握到什么程度,你看下我的论文内容就知道了,希望对你的编程有帮助。
Everyone knows computer sorting have many kinds,for example,Bubble Sort、Quick Sort、Selection sort,Shell Sort。So many kinds of methods,how many you really controled?Such as Bubble Sort is used in science field and accepted by many programmers;QuickSort is a sort changed from Bubble Sort;Selection Sort is an simple and perceptual intution and Shell Sort is an kind of Inserting sort。Everyone can choose an sort according to their own mastery of knowledge and demand for their needs.Now what I want to explain is Binary sort,maybe you can say that it was so easy understanded or searched from the web,listened your concept,I want to say you are wrong。Now I will use example telling you my ideas and hope can be useful for you。
程序需求:
考虑排序一手扑克牌的背景,开始时,我们的左手为空并且桌子上的牌面向下。然后,我们每次从桌子上拿走一张牌并将它插入左手中正确的位置。为了找到一张牌的正确位置,我们从右到左将它与已经在手中的每张牌进行比较。拿在左手上的牌总是排好的,直到桌子上的牌被拿完。(不考率花色,自然数排序就可以)
import java.util.ArrayList;
import java.util.List;
public class paixu {
static int counts=0;//计算比较个数
public static List<Integer> binarySort(List<Integer> list,int num){
int high, low, mid;
low=0;//查找区间上界
high=list.size()-1;//查找区间下界
while(low<=high) {
counts++;
mid=(low+high)/2;//找中间值
if(num<list.get(mid)) {//如果待插入记录比中间记录小
high=mid-1;//插入点在低半区
}else {
low=mid+1;
}
}
list.add(low,num);//将待插入记录回填到正确位置
return list;
}
public static void method3(int n) {
List<Integer> list=new ArrayList<Integer>();//用来保存排好序列的数据
// int datas[]= {34,56,23,12,45,67,345};
int datas[]= {789,678,456,345,123,90,89,67,45,34};
for(int i=0;i<n;i++) {
// Random r=new Random();
// int num =r.nextInt(200);
if(list.size()==0) {
list.add(datas[i]);
counts++;
}else {
list=binarySort(list, datas[i]);
}
System.out.print("第"+list.size()+"次的排序结果为:");
for(int j=0;j<list.size();j++) {
System.out.print(list.get(j)+"\t");
}
System.out.println();
}
System.out.println("计算次数为:"+counts);
}
public static void main(String[] args) {
method3(10);
}
}
程序的思路就是用二分治的思想进行排序,但不同于原来的思想的是,原有的是对数字集合进行排序,我现在的做法是对已经排好的数字集合插入数据,并且要排序,因为前面的数据已经排好了,再插入新数据时只需要排序插入的数据即可。
————————————————
版权声明:本文为CSDN博主「piaoyiren」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/piaoyiren/article/details/112761152