复习了一下冒泡排序和选择排序,如下代码:
public class Sort {
//冒泡排序:
public static int[] mpSort(int a[]){
for (int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
int temp = 0;
if(a[i]>a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a;
}
//选择排序
public static int[] selectSort(int a[]){
for(int i=0;i<a.length-1;i++){
int minIndex = i;
for(int j=i+1;j<a.length;j++){
if(a[j]<a[minIndex]){
minIndex = j;
}
}
int temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
return a;
}
public static void main(String args[]){
int a[] = {7,8,6,2,5};
a = mpSort(a);
a = selectSort(a);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}
本文介绍了两种基本的排序算法——冒泡排序和选择排序,并提供了具体的Java实现代码。通过对比这两种排序方法,读者可以更好地理解它们的工作原理及适用场景。
1036

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



