Basic sorting algorithm

Source: Internet
Author: User

Quick sort (n*lgn unstable): Randomly select a number x in the array (choose the last one here), divide the array into two parts that are smaller than x and X, and repeat the algorithm for the remaining two parts until the end.

def Quick_sort (a)   = A.pop)? Quick_sort (a.select{|i| i <= x}) + [x] + quick_sort (a.select{|i| i > x}): []end

Bubble sort (n^2 Stable): if a[n] > a[n+1] is swapped, the maximum value after the bubble sort is placed at the end, and then the first n-1 item is then bubbled up in sequence.

def Bubble_sort (a)  (A.length if a[j]>a[j+1]}}end

Select sort (n^2 unstable): Select the minimum value in N to insert the array front end, and then find the smallest value in the next n-1 item in the array second.

def Selection_sort (a)  | i| # Select the index of thenext smallest element          # Swap   endend

Insert sort (n^2 Stable): Creates a new sorted array at the beginning of the array, and then inserts the corresponding position of the previously sorted array for each newly scanned value that follows.

def Insertion_sort (a)  (1...a.length). Each do |i|    if a[i-1] > a[i]      #Storethe number to be inserted      j = I       C12>while and a[j-1] > temp        #move every elements in the array which is greater than the inserted number forward        J-= 1      end      #Insert the number    end  EndEnd

Basic sorting algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.