常见写法:1、基本冒泡排序;2、改进后的冒泡排序:由于每次外层循环都会将最大的数移到正确的位置,所以内层循环的次数可以减少,从而提高效率;3、插入排序与冒泡排序结合:这种写法借鉴了插入排序的思想,通过将已排序的元素逐步向前移动,使未排序的元素逐渐有序。这种方法称为“鸡尾酒排序”。
本教程操作系统:windows10系统、Dell G3电脑。
冒泡排序是一种简单的排序算法,它重复地遍历待排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
以下是几种常见的冒泡排序的Java实现:
1、基本冒泡排序:
java
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; 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、改进后的冒泡排序:由于每次外层循环都会将最大的数移到正确的位置,所以内层循环的次数可以减少,从而提高效率。
java
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
boolean swapped = false;
for (int j = 0; 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、插入排序与冒泡排序结合:这种写法借鉴了插入排序的思想,通过将已排序的元素逐步向前移动,使未排序的元素逐渐有序。这种方法称为“鸡尾酒排序”。
java
public 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 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冒泡排序的几种常见写法的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!