package 集合;
/*各种排序算法比较
1.稳定性比较
插入排序、冒泡排序、二叉树排序、二路归并排序及其他线形排序是稳定的;
选择排序、希尔排序、快速排序、堆排序是不稳定的。*/
//选择排序
public class SelectionSort {
public void sort(int[] arr){
int temp;
//两层for循环嵌套,注意:里面的y是要比i大1,长度是一样的。
for(int i=0;i<arr.length;i++){
for(int y=i+1;y<arr.length;y++){
if (arr[i]>arr[y]) {
//先用反例>于号判断,两个交换,用一个中间值
temp = arr[i];
arr[i] = arr[y];
arr[y] = temp;
}
}
}
//打印数组,有三种方法
for(int a:arr){
System.out.print(a+",");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] array = {1,12,2,5,556,27,66,76,23,43};
SelectionSort SS =new SelectionSort();
SS.sort(array);
}
}
//冒泡排序
public class BubbleSort {
public void sort(int[] arr){
int temp;
for (int i = 0; i < arr.length-1; i++) { //第一个for循环控制排序要走多少趟,最多做n-1趟排序
for (int j = 0; j < arr.length-1-i; j++) {
if(arr[j]>arr[j+1]){ //在剩下的数里面把大的往后排,小的往前排,后面的一定比前面,这是确实能定性的
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
//打印数组,有三种方法
for(int a:arr){
System.out.print(a+",");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] array = {1,12,2,5,556,27,66,76,23,43};
BubbleSort maopao =new BubbleSort();
maopao.sort(array);
//System.out.println(Arrays.toString(array));
}
}
简单的选择排序和冒泡排序算法
最新推荐文章于 2023-10-03 11:53:44 发布