/**
* introduction to algorithms, second edition
* 6.4 heapsort
* @author 土豆爸爸
* */
public class heapsort
}
/**
* 構建max heap
*
*/
private void buildmaxheap()
}
/**
* 使陣列的第i個元素按max heap規則重排
* @param i
* 元素索引
*/
private void maxheapify(int i) else
if (r < heapsize && array[r] > array[largest])
if (largest != i)
}
/**
* 計算結點索引為i的元素的左子結點的索引
* @param i
* 當前索引
* @return 左子結點的索引
*/
private int left(int i)
/**
* 計算結點索引為i的元素的右子結點的索引
* @param i
* 當前索引
* @return 右子結點的索引
*/
private int right(int i)
}import junit.framework.testcase;
public class heapsorttest extends testcase ;
heapsort heapsort = new heapsort();
heapsort.sort(array);
asserttrue(verifyordered(array));
}
public void testrandomarray()
heapsort heapsort = new heapsort();
heapsort.sort(array);
asserttrue(verifyordered(array));
}
private boolean verifyordered(int array)
}
return true;
}
}
演算法導論示例 InsertSort
introduction to algorithms,second edition 2.1 insertsort author 土豆爸爸 public class insertsort array i 1 key import junit.framework.testcase public clas...
演算法導論示例 MergeSort
introduction to algorithms,second edition 2.3 mergesort author 土豆爸爸 public class mergesort public static void merge int array,int p,int q,int r l i in...
演算法導論示例 PermuteBySorting
introduction to algorithms,second edition 5.3 permute by sorting author 土豆爸爸 public class permutebysorting 根據隨機陣列對目標資料進行排序 sort array,p 根據p對array重排 pa...
演算法導論示例 QuickSort
introduction to algorithms,second edition 7.1 quicksort author 土豆爸爸 public class quicksort 找到一個位置q,使q左邊的元素都比q小,q右邊的元素都比q大 param array 待排序陣列 param p 開始...
演算法導論示例 Queue
introduction to algorithms,second edition 10.1 queues author 土豆爸爸 public class queue 將元素x新增到佇列。佇列的尾索引加1。param x 待新增的元素 public void enqueue int x array...