排序算法

常见排序算法

本文涉及的算法有:

  • 冒泡排序
  • 选择排序
  • 计数排序

冒泡排序

  • 伪代码
语法定义: "<-" 赋值符号  a[0]会转换为a['0']
a <- {
    '0': 6,
    '1': 1,
    '2': 3,
    '3': 5,
    '4': 2,
    '5': 4,
    'length': 6
}
// 当前循环次数
n <- 1
while (n < a['length'])
    // 当前选中的数字下标 
    index <- 0
    while (index < a['length'] - n)
        if (a[index] < a[index+1])
            index <- index+1
        else
            c <- a[index]
            a[index] <- a[index+1]
            a[index+1] <- c
            index <- index+1
        end
        n <- n+1
    end
end
print a
end
    
  • 流程图
image

选择排序

  • 伪代码
a <- {
    '0': 3,
    '1': 1,
    '2': 6,
    '3': 4,
    '4': 5,
    '5': 2,
    'length': 6
}
// 当前轮数
n = 1
while(n < a['length'])
    minIndex = n - 1
    index = minIndex + 1
    if (index < a['length'])
        if (a[minIndex] < a[index])
            index = index + 1
        else
            minIndex = index
            index = index + 1
        end
    else
        t = a[n - 1]
        a[n - 1] = a[minIndex]
        a[minIndex] = t
        n = n + 1
    end
end
print a
end
  • 流程图
image

计数排序

  • 伪代码
a <- {
    '0':0,
    '1':2,
    '2':1,
    '3':56,
    '4':3,
    '5':67,
    '6':3,
    'length':7
}
// length 是数组最大数字加1, 如果存在'66': 1, 那么length 就是 67

hash <- {   
}

index <- 0
while(index < a['length'])
    number <- a[index] 
    if hash[number] == undefined
        hash[number] <- 1
    else
        hash[number] <- hash[number] + 1
    end
    index <- index + 1
end

hash <- {
    '0':1,
    '1':1,
    '2':1,
    '3':2,
    '56':1,
    '67':1
}

index2 <- 0
max <- findMax(a) // a中最大值是67, hash的length就是68, 从0开始, '0':1, '1':1 ..... '67':1
newArr <- {}

while(index2 <= max)
    count <- hash[index2]
    if count != undefined
        countIndex = 0
        while(countIndex < count)
            newArr.push(index2)
            countIndex <- countIndex + 1
        end
    end
    index2 <- index2 + 1
end
print newArr
  • 流程图
image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文首发于我的个人博客:尾尾部落 排序算法是最经典的算法知识。因为其实现代码短,应该广,在面试中经常会问到排序算法...
    繁著阅读 9,999评论 3 118
  • 前言 查找和排序算法是算法的入门知识,其经典思想可以用于很多算法当中。因为其实现代码较短,应用较常见。所以在面试中...
    宝塔山上的猫阅读 4,719评论 1 21
  • 今天妆令人特别着迷 出门前换上新的心情…… 听着最近流行的(带你去旅行),记录下此刻的心情! 乘车前往富阳龙门古镇...
    小灰灰日常阅读 3,008评论 2 0
  • 第一次接触东野圭吾的作品,是大学时候看的白夜行的日剧,当时一天就刷完了,让人知道,原来最深刻的爱情可以为她的粉身碎...
    鱼耗子阅读 1,137评论 0 0
  • 前几天刚看到温州女孩遇害的消息,我还不敢相信又是在滴滴平台出的事情,这不是才过去三个月吗? 滴滴和快滴这类网约车刚...
    冰罐头阅读 2,405评论 0 0