常見寫法:1、基本冒泡排序;2、改進後的冒泡排序:由於每次外層循環都會將最大的數移到正確的位置,所以內層循環的次數可以減少,從而提高效率;3、插入排序與冒泡排序結合:這種寫法借鑒了插入排序的思想,透過將已排序的元素逐步向前移動,使未排序的元素逐漸有序。這種方法稱為「雞尾酒排序」。
本教學作業系統:windows10系統、Dell G3電腦。
冒泡排序是一種簡單的排序演算法,它重複地遍歷待排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。遍歷數列的工作是重複地進行直到沒有再需要交換,也就是說該數列已經排序完成。
以下是幾個常見的冒泡排序的Java實作:
##1、基本冒泡排序:
javapublic static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // swap arr[j+1] and arr[j] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
2、改進的冒泡排序:由於每次外層循環都會將最大的數移到正確的位置,所以內層循環的次數可以減少,從而提高效率。
javapublic static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { boolean swapped = false; for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // swap arr[j+1] and arr[j] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } // If no two elements were swapped by inner loop, then the array is sorted if (!swapped) break; } }
3、插入排序與冒泡排序結合:這種寫法借鑒了插入排序的思想,透過將已排序的元素逐步向前移動,使未排序的元素逐漸有序。這種方法稱為「雞尾酒排序」。
javapublic static void cocktailSort(int[] arr) { int n = arr.length; boolean swapped; // to flag if any swap has been made in a pass for (int i = 0; i < n - 1; i++) { swapped = false; // assume this pass will do nothing for (int j = 0; j < n - 1 - i; j++) { // start with the second last element and go to the last one if (arr[j] > arr[j + 1]) { // if the current element is greater than the next one, swap them int temp = arr[j]; // swap elements arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; // flag to indicate a swap has been made in this pass } } // if no two elements were swapped in this pass, then the array is sorted, so we can stop the sorting process if (!swapped) break; // no swaps means the array is sorted, so we can stop the sorting process. This optimization is not required for correctness, but it can help in practice. If the array is already sorted, the outer loop will keep making passes without making any swaps, so we can stop early. This optimization can be applied to any version of bubble sort
以上是java冒泡排序的幾種常見寫法的詳細內容。更多資訊請關注PHP中文網其他相關文章!