zoukankan      html  css  js  c++  java
  • java数据结构与算法(一)----数组简单排序

    ========选择排序、冒泡排序、插入排序=======

    1.选择排序:

      将数组中的每一个元素与第一个元素比较,如果这个元素比第一个小,则交换两个数的位置

      将数组中第二个元素之后的元素与第二个元素比较,如果这个元素比第二个小,则交换两个数的位置

      ...

      结果n-1次比较完成排序

    public class SortDemo{
        public static void main(String[] args){
            int[] ary={8,2,3,4,71,4};
            ary=selectionSort(ary);
        }
        public static int[] selectionSort(int[] ary){
            for(int i=0;i<ary.length-1;i++){
                for(int j=i+1;j<ary.length-1;j++){
                    if(ary[i]>ary[j]){
                        int temp=ary[i];
                        ary[i]=ary[j];
                        ary[j]=temp;
                    }
                }    
            }

        return ary;
        }
    }

    2.冒泡排序

      比较相邻的两个元素,将小的放在前面

    public class SortDemo{
        public static void main(String[] args){
            int[] ary={8,2,3,4,71,4};
            ary=selectionSort(ary);
        }
        public static int[] selectionSort(int[] ary){
            for(int i=0;i<ary.length-1;i++){
                for(int j=0;j<ary.length-i-1;j++){
                    if(ary[j]>ary[j+1]){
                        int temp=ary[j];
                        ary[j]=ary[j+1];
                        ary[j+1]=temp;
                    }
                }    
            }
            return ary;
        }
    }

    3.插入排序

      将数组分为两部分,将后部分的第一个逐一与前部分每一个元素比较,在合理位置插入

      插入排序效率高于选择排序和冒泡排序

    public class SortDemo{
        public static void main(String[] args){
            int[] ary={8,2,3,4,71,4};
            ary=selectionSort(ary);
        }
        public static int[] selectionSort(int[] ary){
            for(int i=1;i<ary.length;i++){
                int t=ary[i]
                for(int j=i-1;j>=0;j--){
                    if(t<ary[j]){
                        ary[j+1]=ary[j];
                    }else{
                        break;
                    }
                }    
                ary[j+1]=t;
            }
            return ary;
        }
    }

      

  • 相关阅读:
    图片上传-下载-删除等图片管理的若干经验总结3-单一业务场景的完整解决方案
    图片上传-下载-删除等图片管理的若干经验总结2
    HDU 1195 Open the Lock
    HDU 1690 Bus System
    HDU 2647 Reward
    HDU 2680 Choose the best route
    HDU 1596 find the safest road
    POJ 1904 King's Quest
    CDOJ 889 Battle for Silver
    CDOJ 888 Absurdistan Roads
  • 原文地址:https://www.cnblogs.com/shenming/p/3630917.html
Copyright © 2011-2022 走看看