Basic Sorting Algorithms
生活随笔
收集整理的這篇文章主要介紹了
Basic Sorting Algorithms
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
*穩(wěn)定指原本數(shù)列中相同的元素的相對(duì)前后位置在排序后不會(huì)被打亂
快速排序(n*lgn 不穩(wěn)定):數(shù)組中隨機(jī)選取一個(gè)數(shù)x(這里選擇最后一個(gè)),將數(shù)組按比x大的和x小的分成兩部分,再對(duì)剩余兩部分重復(fù)這個(gè)算法直到結(jié)束。但在數(shù)據(jù)量小的時(shí)候表現(xiàn)差。
def quick_sort(a)(x = a.pop) ? quick_sort(a.select{|i| i <= x}) + [x] + quick_sort(a.select{|i| i > x}) : [] end冒泡排序(n^2 穩(wěn)定):如果a[n] > a[n+1] 則調(diào)換,冒泡排序一遍后的最大的值會(huì)被放在最后,然后依次對(duì)前n-1項(xiàng)再進(jìn)行冒泡排序。
def bubble_sort(a)(a.length-2).downto(0) {|i| i.times{|j| a[j],a[j+1] = a[j+1],a[j] if a[j]>a[j+1]}} end選擇排序(n^2 不穩(wěn)定):在n中選擇最小值插入數(shù)組前端,然后再在后n-1項(xiàng)中找最小值放在數(shù)組第二個(gè)。
def selection_sort(a)a.length.times do |i|t = a.index(a[i..-1].min) #select the index of the next smallest elementa[i], a[t] = a[t], a[i] #swap end end插入排序 (n^2 穩(wěn)定):在數(shù)組開始處新建一個(gè)排序好的數(shù)組,然后對(duì)于之后的每個(gè)新掃描的值,插入之前排序好的數(shù)組的相應(yīng)位置。
def insertion_sort(a)(1...a.length).each do |i|if a[i-1] > a[i]temp = a[i] #store the number to be insertedj = iwhile j > 0 and a[j-1] > tempa[j] = a[j-1] #move every elements in the array which is greater than the inserted number forwardj -= 1enda[j] = temp #insert the number endend end轉(zhuǎn)載于:https://www.cnblogs.com/lilixu/p/4587307.html
總結(jié)
以上是生活随笔為你收集整理的Basic Sorting Algorithms的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用FIR.im发布自己的移动端APP
- 下一篇: 流程控制 - PHP手册笔记