• 数组排序算法


    数组排序算法

    (一)冒泡排序

    基本思想:对比相邻的元素值,如果满足条件就交换元素值,把较小的元素移动数组前面,较大的元素移动到数组后面
    算法:
    冒泡算法由双层循环实现,其中外层循环控制排序轮次,一般为排序的数组长度减一。而内层循环主要用于对比数组中每个临近元素的大小,以确定是否交换位置,对比和交换的次数随排序轮数而减少。

    算法实现:

     1 public class Bubble {
     2     public static void main(String[] args){
     3         int[] array ={63,4,24,1,3,15};
     4         Bubble sorter = new Bubble();
     5         sorter.sort(array);
     6     }
     7     //冒泡排序
     8     public void sort(int[] array){
     9         for(int i=1;i<array.length;i++){  //排序轮次,数组长度-1
    10             for(int j=0;j<array.length-i;j++){ //内层比较,每过一轮末尾少比较一个
    11                 if(array[j]>array[j+1]){
    12                     int temp =array[j];
    13                     array[j]=array[j+1];
    14                     array[j+1]=temp;
    15                 }
    16             }
    17         }
    18         showArray(array);
    19     }
    20     //显示数组元素
    21     public void showArray(int[] array){
    22         for(int i:array){
    23             System.out.print(i+" ");
    24         }
    25     }
    26 }

    (二)直接选择排序

    速度比冒泡排序快一些
    基本思想:将指定排序位置与其他数组元素分别对比,如果满足条件就交换元素值。
    举例:
    初始值:63 4 24 1 3 15
    第一轮:15 4 24 1 3 63
    第二轮:15 4 3 1 24 63
    第三轮:1 4 3 15 24 63
    第四轮:1 3 4 15 24 63
    第五轮:1 3 4 15 24 63
    解释:首先找出6个数中最大的与最后一个数交换位置,然后在前5个数中找出最大的数与倒数第二个交换位置,这样length-1次

    算法实现:

     1 public class Select {
     2     public static void main(String[] args){
     3         int array[]={63,4,24,1,3,15};
     4         Select sorter =new Select();
     5         sorter.sort(array);
     6     }
     7     //直接选择排序
     8     public void sort(int[] array){
     9         int index;
    10         for(int i=1;i<array.length;i++){  //排序轮次仍为数组长度-1
    11             index=0;
    12             for(int j=1;j<=array.length-i;j++){ //内层比较,找出最大数的位置
    13                 if(array[j]>array[index]){
    14                     index=j;
    15                 }
    16             }
    17             int temp=array[array.length-i];
    18             array[array.length-i]=array[index];
    19             array[index]=temp;
    20         }
    21         showArray(array);
    22     }
    23     //显示数组
    24     private void showArray(int[] array) {
    25         for(int i:array){
    26             System.out.print(i+" ");
    27         }
    28     }
    29 }
    务实,说实话!
  • 相关阅读:
    redis实时同步工具redis-shake
    elasticsearch单机部署
    ogg从库进程监控
    mha安装部署
    mha自定义路径安装
    gnuplot输出柱状图
    gnuplot输出曲线图
    gnuplot命令行模式不支持中文标题的解决办法
    ogg中logdump使用自动输入执行
    JDK(java se development kit)的构成
  • 原文地址:https://www.cnblogs.com/xtuxiongda/p/8460731.html
Copyright © 2020-2023  润新知