"景先生毕设|www.jxszl.com

JAVA面试最常见的两种排序算法

2023-09-12 15:40编辑: www.jxszl.com景先生毕设
JAVA面试最常见的两种排序算法
冒泡排序(Bubble Sort)
原理:比较相邻的元素。如果第一个比第二个大,就交换他们两个。
           持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
public class BubbleSort{
     public static void main(String[] args){
         int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
         for (int i = 0; i < score.length -1; i++){    //最多做n-1趟排序
             for(int j = 0 ;j < score.length - i - 1; j++){    //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
                 if(score[j] < score[j + 1]){    //把小的值交换到后面
                     int temp = score[j];
                     score[j] = score[j + 1];
                     score[j + 1] = temp;
                 }
             }            
             System.out.print("第" + (i + 1) + "次排序结果:");
             for(int a = 0; a < score.length; a++){
                 System.out.print(score[a] + "\t");
             }
             System.out.println("");
         }
             System.out.print("最终排序结果:");
             for(int a = 0; a < score.length; a++){
                 System.out.print(score[a] + "\t");
        }
     }
 }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 选择排序(SelectionSort)
原理:每一趟从待排序的记录中选出最小的元素,顺序放在已排好序的序列最后,直到全部记录排序完毕。
public class SelectionSort {
    public static void main(String[] args) {
        int[] arr={1,3,2,45,65,33,12};
        System.out.println("交换之前:");
        for(int num:arr){
            System.out.print(num+" ");
        }        
        //选择排序的优化
        for(int i = 0; i < arr.length - 1; i++) {// 做第i趟排序
            int k = i;
            for(int j = k + 1; j < arr.length; j++){// 选最小的记录
                if(arr[j] < arr[k]){ 
                    k = j; //记下目前找到的最小值所在的位置
                }
            }
            //在内层循环结束,也就是找到本轮循环的最小的数以后,再进行交换
            if(i != k){  //交换a[i]和a[k]
                int temp = arr[i];
                arr[i] = arr[k];
                arr[k] = temp;
            }    
        }
        System.out.println();
        System.out.println("交换后:");
        for(int num:arr){
            System.out.print(num+" ");
        }
    }

原文链接:http://www.jxszl.com/biancheng/JAVA/446603.html