前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >冒泡,选择,插入三排序 顶

冒泡,选择,插入三排序 顶

作者头像
算法之名
发布2019-08-20 10:51:15
2500
发布2019-08-20 10:51:15
举报
文章被收录于专栏:算法之名算法之名

这三种排序的时间复杂度都是指数级的,所以在实际项目中并不推荐。

代码语言:javascript
复制
/**
 * Created by Administrator on 2018-02-17.
 */
public class Sort {
    static final int SIZE = 10;
    public static void BubbleSort(int[] a) {
        int temp;
        if(a.length > 1) {
            for (int i = 1; i < a.length; i++) {
                for (int j = 0;j < a.length - i;j++) {
                    if(a[j] > a[j+1]) {
                        temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                    }
                }
                System.out.print("第" + i +"步排序结果:");
                for (int k = 0;k < a.length;k++) {
                    System.out.print(" " + a[k]);
                }
                System.out.print("\n");
            }
        }
    }
代码语言:javascript
复制
   public static void selectSort(int[] a) {
    int index;
    int temp;
    for (int i = 0;i < a.length - 1;i++) {
        index = i;
        for (int j = i + 1;j < a.length;j++) {
            if(a[j] < a[index]) {
                index = j;
            }
        }
        if(index != i) {
            temp = a[i];
            a[i] = a[index];
            a[index] = temp;
        }
        System.out.print("第" + i + "步排序结果:");
        for (int h = 0;h < a.length;h++) {
            System.out.print(" " + a[h]);
        }
        System.out.print("\n");
    }
}
代码语言:javascript
复制
public static void insertionSort(int[] a) {
    int i,j,t,h;
    for (i = 1;i < a.length;i++) {
        t = a[i];
        j = i - 1;
        while (j >= 0 && t < a[j]) {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = t;
        System.out.print("第" + i + "步排序结果:");
        for (h = 0;h < a.length;h++) {
            System.out.print(" " + a[h]);
        }
        System.out.print("\n");
    }
}
代码语言:javascript
复制
public static void main(String[] args) {
        int[] shuzu = new int[SIZE];
        int i;
        for (i = 0;i < SIZE;i++) {
            shuzu[i] = (int)(100 + Math.random() * (100 + 1));
        }
        System.out.print("排序前的数组为:\n");
        for (i = 0;i <SIZE;i++) {
            System.out.print(shuzu[i] + " ");
        }
        System.out.print("\n");
        BubbleSort(shuzu);      //selectSort或者insertionSort
        System.out.print("排序后的数组为:\n");
        for (i = 0;i < SIZE;i++) {
            System.out.print(shuzu[i] + " ");
        }
        System.out.print("\n");
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档