Android开发日记:好久没写的冒泡排序

最近在开发时遇到一个需求,给定一个 ListA 集合,里面存储不定长度的 String 字符串,通过网络请求获取另外一串 ListB 数据,读取 ListB ,将 ListB 中含有 ListA 中字符串的数据放到集合前方,将不含有相关数据的放入后方

开发业务久了,第一反应是

1.  先循环 ListB 的每个值,将符合 ListA 的数据提取出来,使用一个临时的 List 进行存储

2.  这个时候 ListB 中的数据都是不含有 ListA 的,将 ListB 剩下的数据放入临时 List

3.  将临时 List 的数据覆盖到 ListB

代码如下:

private fun sortSearch(ListA: MutableList, ListB: MutableList) :MutableList{
    val tempList = mutableListOf()
    ListB.forEach { itB ->
        ListA.firstOrNull { itB.contains(it) }?.let { tempList.add(itB) }
    }
    ListB.removeAll(tempList)
    tempList.addAll(ListB)
    return tempList
}


但是仔细一想,这不是可以直接用最基础的冒泡排序吗

思路如下:

1.  定义两个临时变量,一个记录符合条件的 index 值,另外一个记录不符合条件的 index

2.  循环 ListB ,获取第一个符合条件的 index 和第一个不符合条件的 index 值,将他们赋值给临时变量

3.  每次对比两个临时变量的值,如果符合条件的 index 值大于不符合的则将他们的位置和 index 值进行调换

代码如下:

private fun sortOfBubble(listA: List): MutableList {
    val tempList = listA.toMutableList()
    var indexOfProduct = -1
    var indexOfNot = -1
    tempList.forEachIndexed { index, string ->
        run product@{
            listB.forEach {
                if (string.contains(it)) {
                    indexOfProduct = index
                    return@product
                }
            }
            if (indexOfNot == -1) indexOfNot = index
        }
        if (indexOfNot != -1 && indexOfProduct != -1 && indexOfProduct > indexOfNot) {
            val temp = tempList[indexOfProduct]
            tempList[indexOfProduct] = tempList[indexOfNot]
            tempList[indexOfNot] = temp
            indexOfNot = indexOfProduct
        }
    }
    return tempList
}



请使用浏览器的分享功能分享到微信等