本文共 1812 字,大约阅读时间需要 6 分钟。
JAVA的冒泡排序算法,代码如下:
package test;
public class MaoPaoSort { public static void main(String[] args) { oneMethod(); System.out.println(); twoMethod(); System.out.println(); threeMethod(); System.out.println(); fourMethod(); } /** * 冒泡排序从小到大1 */ public static void oneMethod() { int array[] = { 3, 7, 5, 12, 87, 116, 1, 53 }; // 需要进行array.length-1次排序。 for (int i = 1; i <= array.length - 1; i++) { // 每次排序都将把当前最大的数放到后面。 for (int j = 0; j < array.length - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i] + " "); } } /** * 冒泡排序从小到大2 */ public static void twoMethod() { int array[] = { 3, 7, 5, 12, 87, 116, 1, 53 }; // 需要进行array.length-1次排序。 for (int i = 0; i < array.length - 1; i++) { // 每次排序都将把当前最小的数放到前面。 for (int j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i] + " "); } } /** * 冒泡排序从大到小3 */ public static void threeMethod() { int array[] = { 3, 7, 5, 12, 87, 116, 1, 53 }; for (int i = 0; i < array.length - 1; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] < array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i] + " "); } } /** * 冒泡排序从大到小4 */ public static void fourMethod() { int array[] = { 3, 7, 5, 12, 87, 116, 1, 53 }; for (int i = 1; i <= array.length - 1; i++) { for (int j = 0; j < array.length - i; j++) { if (array[j] < array[j + 1]) { int temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } } for (int i = 0; i < array.length; i++) { System.out.print(" " + array[i] + " "); } } }转载地址:http://ybmxi.baihongyu.com/