package study;
public class 冒泡排序 {
public static void bubbleSort(int[] arr) {
/**
* 7 1 3 2 5 4 6
* 0 1 2 3 4 5 6
*
* 0 - 6 找最大
* 0 - 5 找最大
* 0 - 4 找最大
* 0 - 3
* 0 - 2
* 0 - 1
* 0 - 0
*
* 0 - N-1
* 0 - N-2
* ......
* 0 - N-N
*
*/
int N = arr.length;
for (int end = N -1; end >= 0 ; end--) {
// 0 - 6 找最大 0-1 1-2 2-3 3-4 end-1 end
for (int second = 0; second < end; second++) {
if (arr[second] > arr[second + 1]) {
swap(arr,second+1,second);
}
}
}
}
public static void swap(int[] arr,int i,int j) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {7,1,3,2,5,4,6,1,2,5,6,3};
// 1、原数组输出
printArray(arr);
// 2、冒泡排序
bubbleSort(arr);
// 3、排序数组输出
printArray(arr);
}
}
数据结构与算法 冒泡算法
最新推荐文章于 2024-06-14 09:55:36 发布