从零开始学数据结构和算法(一)冒泡与选择排序

23 阅读3分钟
  • 代码实现

public static void bubbleSort(int[] array){ //3 1 5 8 2 9 4 6 7 n*(n-1)/2 n for(int i=array.length-1;i>0;i--) { boolean flag=true; for (int j = 0; j < i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; flag=false; } } if(flag){ break; } } }

  • 使用场景

  • 数据量足够小,比如斗牛游戏的牌面排序

选择排序算法

  • 简介

选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。

  • 动画演示

  • 算法步骤
  1. 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
  2. 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
  3. 重复第二步,直到所有元素均排序完毕。
  • 代码实现

/** *选择排序 */ public void selectSort(int[] arr) { for (int j = 0; j < arr.length - 1; j++) { //定义一个最小值 int min = j; for (int i = min + 1; i < arr.length; i++) { if (arr[i] < arr[min]) { min = i; } } //如果第一位已经是最小值了就不用替换了 一定保证程序达到最优; if (min != j) { int temp = arr[j]; arr[j] = arr[min]; arr[min] = temp; } } }

  • 使用场景

快速排序的基础

参考例子

利用蛮力法给牌进行排序(冒泡排序)

  • 编写 卡片 > 牌 数据 model

/**

  • 牌的数据 Bean

*/ public class Cards implements Comparable{ public int pokerColors;//花色 public int cardPoints;//点数

public Cards(int pokerColors, int cardPoints) { this.pokerColors = pokerColors; this.cardPoints = cardPoints; } //提供一个方法,用来比较对象的大小 @Override public int compareTo(@NonNull Object o) { Cards c=(Cards)o; if(this.cardPoints>c.cardPoints){ return 1; }else if(this.cardPoints<c.cardPoints){ return -1; } if(this.pokerColors>c.pokerColors){ return 1; }else if(this.pokerColors<c.pokerColors){ return -1; } return 0; }

@Override public String toString() { return "Cards{" + "pokerColors=" + pokerColors + ", cardPoints=" + cardPoints + '}'; }

}

  • 卡片进行排序

public void testCards() { Cards [] cards = {new Cards(3,9),new Cards(1,10),new Cards(2,6)}; for (int i = cards.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (cards[j].compareTo(cards[j+ 1] ) > 0 ){ Cards temp =cards[j]; cards[j] = cards[j+1]; cards[j+1] = temp; } } } }

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2021最新上万页的大厂面试真题

七大模块学习资料:如NDK模块开发、Android框架体系架构...

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群: **第一,**学习知识比较碎片化,没有合理的学习路线与进阶方向。 **第二,**开发几年,不知道如何进阶更进一步,比较迷茫。 第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢! 由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示 。如有需要获取完整的资料文档的朋友点击我的GitHub免费获取。