共計 2670 個字符,預計需要花費 7 分鐘才能閱讀完成。
本篇內容主要講解“Java 選擇排序的方法是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓丸趣 TV 小編來帶大家學習“Java 選擇排序的方法是什么”吧!
public class SelectSort { public static void main(String[] args) { int[] nums = {49,38,65,97,76,13,27,49};
// simpleSelectSort(nums);
// treeSelectSort(nums);
heapSelectSort(nums);
for (int num:nums) {
System.out.print(num+ \t
}
}
簡單排序處理流程
(1)從待排序序列中,找到關鍵字最小的元素;(2)如果最小元素不是待排序序列的第一個元素,將其和第一個元素互換;(3)從余下的 N - 1 個元素中,找出關鍵字最小的元素,重復 (1)、(2) 步,直到排序結束。 static void simpleSelectSort(int[] nums){//7,6,3,4,5
for (int i = 0; i nums.length; i++) {
int minIndex = i;
for (int j = i+1; j nums.length; j++) { if (nums[minIndex] nums[j]) {
minIndex = j;
}
}
if (minIndex!=i) { int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
}
}
}
static void treeSelectSort(int[] nums){//19 , 38 , 65 ,97 , 76 ,13 , 27 , 49
int len = nums.length;
int treeSize = 2*len - 1; // 滿二叉樹的節點數
int low = 0;
int[] tree = new int[treeSize];// 臨時的樹存儲空間
// 由后向前填充此樹,索引從 0 開始
for (int i = len -1,j = 0;i = 0;--i,j++){// 填充葉子節點
tree[treeSize - 1 - j] = nums[i];
}
for (int x:tree) {
System.out.print(x+ \t
}
System.out.println();
for (int i = treeSize - 1; i 0; i -=2){// 填充非終端節點
// System.out.println(i+ --- +((i - 1)/2));
tree[(i-1)/2] = (tree[i - 1] tree[i] ? tree[i - 1] : tree[i]);
}
for (int x:tree) {
System.out.print(x+ \t
}
System.out.println();
// 不斷移走最小節點
int minIndex;
while (low len){ int min = tree[0]; // 最小值
nums[low++] = min;
minIndex = treeSize - 1;
while(tree[minIndex] != min){// 不斷移走最小節點
minIndex--;
}
tree[minIndex] = Integer.MAX_VALUE;// 設置一個最大值標志
// 找到其兄弟節點
while (minIndex 0){// 如果其還有父節點 -- 該步驟旨在重新生成一顆樹
if (minIndex % 2 == 0){// 如果是右節點
tree[(minIndex - 1)/2] = (tree[minIndex - 1] tree[minIndex] ? tree[minIndex - 1] : tree[minIndex]);
minIndex = (minIndex-1)/2;
} else {// 如果是左節點
tree[minIndex/2] = (tree[minIndex] tree[minIndex + 1] ? tree[minIndex] : tree[minIndex + 1]);
minIndex = minIndex/2;
}
}
// for (int x:tree) {
// System.out.print(x+ \t
// }
// System.out.println();
}
}
static void heapSelectSort(int[] nums){
int len = nums.length;
// 構建堆
for (int i = (len -1)/2; i = 0; i--) { heapAdjust(nums,i,len);
}
// 輸出堆頂元素并調整建新堆的過程
int count = len-1;
while(count 0 ){
// 交換樹根與最后一個值
swap(nums,0,count);
count -- ;
heapAdjust(nums,0,count);
}
}
static void heapAdjust(int[] nums, int i, int len) { int parent = nums[i];
for (int j = (i+1)*2 - 1; j len; j=(j+1)*2 - 1) { if (j len -1 nums[j] nums[j+1]){
++j;
}
if (parent nums[j]){
break;
}
nums[i] = nums[j];
i = j;
}
nums[i] = parent;
}
/**
* 交換數組中兩元素的值
*/
private static void swap(int[] nums,int i,int j){ int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
到此,相信大家對“Java 選擇排序的方法是什么”有了更深的了解,不妨來實際操作一番吧!這里是丸趣 TV 網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
正文完