堆排序最优java代码 堆排序程序( 二 )


面试穿什么,这里找答案!
插入排序Java代码:
public class InsertionSort {
// 插入排序:直接插入排序,希尔排序
public void straightInsertionSort(double [] sorted){
int sortedLen= sorted.length;
for(int j=2;jsortedLen;j++){
if(sorted[j]sorted[j-1]){
sorted[0]= sorted[j];//先保存一下后面的那个
sorted[j]=sorted[j-1];// 前面的那个后移 。
int insertPos=0;
for(int k=j-2;k=0;k--){
if(sorted[k]sorted[0]){
sorted[k+1]=sorted[k];
}else{
insertPos=k+1;
break;
}
}
sorted[insertPos]=sorted[0];
}
}
}
public void shellInertionSort(double [] sorted, int inc){
int sortedLen= sorted.length;
for(int j=inc+1;jsortedLen;j++ ){
if(sorted[j]sorted[j-inc]){
sorted[0]= sorted[j];//先保存一下后面的那个
int insertPos=j;
for(int k=j-inc;k=0;k-=inc){
if(sorted[k]sorted[0]){
sorted[k+inc]=sorted[k];
//数据结构课本上这个地方没有给出判读 , 出错:
if(k-inc=0){
insertPos = k;
}
}else{
insertPos=k+inc;
break;
}
}
sorted[insertPos]=sorted[0];
}
}
}
public void shellInsertionSort(double [] sorted){
int[] incs={7,5,3,1};
int num= incs.length;
int inc=0;
for(int j=0;jnum;j++){
inc= incs[j];
shellInertionSort(sorted,inc);
【堆排序最优java代码 堆排序程序】}
}
public static void main(String[] args) {
Random random= new Random(6);
int arraysize= 21;
double [] sorted=new double[arraysize];
System.out.print("Before Sort:");
for(int j=1;jarraysize;j++){
sorted[j]= (int)(random.nextDouble()* 100);
System.out.print((int)sorted[j]+" ");
}
System.out.println();
InsertionSort sorter=new InsertionSort();
//sorter.straightInsertionSort(sorted);
sorter.shellInsertionSort(sorted);
System.out.print("After Sort:");
for(int j=1;jsorted.length;j++){
System.out.print((int)sorted[j]+" ");
}
System.out.println();
}
}
面试穿什么,这里找答案!
5)交换排序:
包括冒泡排序,快速排序 。
冒泡排序法:该算法是专门针对已部分排序的数据进行排序的一种排序算法 。如果在你的数据清单中只有一两个数据是乱序的话,用这种算法就是最快的排序算法 。如果你的数据清单中的数据是随机排列的,那么这种方法就成了最慢的算法了 。因此在使用这种算法之前一定要慎重 。这种算法的核心思想是扫描数据清单,寻找出现乱序的两个相邻的项目 。当找到这两个项目后,交换项目的位置然后继续扫描 。重复上面的操作直到所有的项目都按顺序排好 。
快速排序:通过一趟排序,将待排序记录分割成独立的两个部分,其中一部分记录的关键字均比另一部分记录的关键字小 , 则可分别对这两部分记录继续进行排序,以达到整个序列有序 。具体做法是:使用两个指针low,high, 初值分别设置为序列的头,和序列的尾,设置pivotkey为第一个记录,首先从high开始向前搜索第一个小于pivotkey的记录和pivotkey所在位置进行交换 , 然后从low开始向后搜索第一个大于pivotkey的记录和此时pivotkey所在位置进行交换,重复知道low=high了为止 。
交换排序Java代码:
public class ExchangeSort {
public void BubbleExchangeSort(double [] sorted){
int sortedLen= sorted.length;
for(int j=sortedLen;j0;j--){
int end= j;
for(int k=1;kend-1;k++){
double tempB= sorted[k];
sorted[k]= sorted[k]sorted[k+1]?
sorted[k]:sorted[k+1];
if(Math.abs(sorted[k]-tempB)10e-6){

推荐阅读