Guest User

Untitled

a guest
Jul 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 0.99 KB | None | 0 0
  1. //quick sort
  2. let quickSort (a : 'a[]) =
  3.    let rand = new Random() //for random pivot chosing
  4.    //swaps elements of array a with indeces i and j
  5.    let swap (a : 'a[]) i j =
  6.         let temp = a.[i]
  7.         a.[i] <- a.[j]
  8.         a.[j] <- temp
  9.    
  10.     //sorts array's a subarray [l; r) in-place
  11.     let rec quickSortRange (a : 'a[]) l r =
  12.        match r - l with
  13.        | 0 | 1 -> ()
  14.        | n ->        
  15.            //preprocess: swap pivot to 1st position
  16.            swap a l <| rand.Next(l, r)
  17.            let p = a.[l]
  18.            //scan and partitioning
  19.            let mutable i = l + 1 //left from i <=> less than pivot part
  20.            for j in (l+1)..(r-1) do
  21.                //preserve invariant: [p|  <p |i >p  |j  unpartitioned  ]
  22.                if a.[j] < p then
  23.                    swap a j i
  24.                    i <- i + 1
  25.            swap a (i-1) l //place pivot in appropriate pos.
  26.            quickSortRange a l (i-1)
  27.            quickSortRange a i r
  28.  
  29.    quickSortRange a 0 a.Length
Add Comment
Please, Sign In to add comment