博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA的冒泡排序算法。
阅读量:4167 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
12月英语--Sowing
查看>>
泛型--datatable TO List
查看>>
存储过程
查看>>
C#之导出excel
查看>>
版本控制--SVN
查看>>
泛型 VS Data Table
查看>>
CSS盒子模型
查看>>
HTML总结(一)
查看>>
3月英语--平平淡淡
查看>>
csf格式转换--逼自己一把
查看>>
ASP控件总结(一)
查看>>
Repeater&Validator控件使用
查看>>
细水翻起半点波涛--4月英语
查看>>
ASP--Active Server Pages Summary
查看>>
常见的电脑病毒
查看>>
站在巨人的肩膀上!
查看>>
2017年5月软考总结
查看>>
Node.js中运行JavaScript代码
查看>>
5月英语总结--I will do it well.
查看>>
认识JS
查看>>