冒泡排序:
package com.wgs;
public class Bubble01 {
public static void main(String[] args) {
int[] num = {4, 2, 3, 6, 9};
//用冒泡排序
B(num);
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}
public static void B(int[] num) {
for (int i = 0; i < num.length - 1; i++) {
for (int j = 0; j < num.length - 1 - i; j++) {
if (num[j] > num[j + 1]) {
int temp;
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
}
//两种冒泡思想之2
public static void C(int[] num) {
for (int i = num.length - 1; i > 0; i--) {
//外部控制次数,内部才是真正的冒泡
for (int j = 0; j < i; j++) {
if (num[j] > num[j + 1]) {
int temp;
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
}
}
选择排序:
package com.wgs;
public class Bubble {
//实现冒泡排序
public static void sort(Comparable[] a) {//需要实现Comparable接口的类
for (int i = 0; i < a.length - 1; i++) {//这里操作的是索引
int minIndex = i;
for (int j = i + 1; j <= a.length - 1; j++) {
//比较索引j和j+1之间的值,内层才真正的到下表
if (greater(a[minIndex], a[j])) {
minIndex = j;
}
}
exchange(a,minIndex,i);
}
}
//比较实现了Comparable接口的两个元素哪一个大
public static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;//返回的true就说明v>w。反之亦然。
}
//数组元素i和j交换位置
public static void exchange(Comparable[] a, int i, int j) {//传进来的当i和j来看的
//交换下表索引
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
选择排序:
package com.wgs;
public class Bubble {
//实现选择排序
public static void sort(Comparable[] a) {//需要实现Comparable接口的类
for (int i = 0; i < a.length - 1; i++) {//这里操作的是索引
int minIndex = i;
for (int j = i + 1; j <= a.length - 1; j++) {
//比较索引j和j+1之间的值,内层才真正的到下表
if (greater(a[minIndex], a[j])) {
minIndex = j;
}
}
exchange(a,minIndex,i);
}
}
//比较实现了Comparable接口的两个元素哪一个大
public static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;//返回的true就说明v>w。反之亦然。
}
//数组元素i和j交换位置
public static void exchange(Comparable[] a, int i, int j) {//传进来的当i和j来看的
//交换下表索引
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
这篇博客详细介绍了两种基本的排序算法——冒泡排序和选择排序。首先,展示了冒泡排序的两种实现方式,通过交换相邻元素来逐步排序数组。接着,解释了选择排序的工作原理,它通过找到剩余部分的最小元素并放到正确位置来完成排序。博客提供了完整的Java代码实现,并且所有排序方法都使用了Comparable接口。
3674

被折叠的 条评论
为什么被折叠?



