Java实现简单的冒泡排序和选择排序
- 冒泡排序:冒泡排序的原理是数组相邻的两元素两两相比,大的沉下去小的浮上来。下面是具体的实现代码:(按从小到大排列)
/**
* 冒泡排序
*/
public static void maopao(int[] b) {
int[] a = b;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = 0;
temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
- 选择排序:第一轮循环中,找出数组中最大或最小的那个元素放在第一位,然后在第二轮循环中就可以从数组中下标为1的元素开始循环找出第二大或第二小的元素放在第二位即可,依次循环即可得到有序的数列,具体的代码如下:(按从大到小排列)
/**
* 选择排序
*/
public static void choice(int[] b) {
int a[] = b;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
int temp = 0;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
整个代码如下:
package cb.tedu;
public class demo6 {
public static void main(String[] args) {
int[] b = { 89, 67, 98, 54, 32, 76, 99 };
maopao(b);
choice(b);
}
/**
* 冒泡排序
*/
public static void maopao(int[] b) {
int[] a = b;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = 0;
temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
/**
* 选择排序
*/
public static void choice(int[] b) {
int a[] = b;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
int temp = 0;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
}