import java.util.Arrays;
/**
*
* @author cnkeysky
*/
public class DemoTest {
public static void main(String[] args) {
int[] arr = {9, -1, 3, 8, 0, -2, 7};
bubbleSort(arr);
System.out.println("排序后:");
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
int len = arr.length;
int l = 0;
int r = len - 1;
while (l < r){
boolean flag = false;
for (int j = l; j < r; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true;
}
}
--r;
for (int j = r; j > l; --j) {
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
flag = true;
}
}
++l;
if (!flag) {
break;
}
System.out.printf("第 %d 次排序: ", l);
System.out.println(Arrays.toString(arr));
}
}
}
双向冒泡-Java
最新推荐文章于 2024-12-19 20:48:19 发布