Skip to content

Commit

Permalink
add: randomized quick sort solution for Miscellaneous
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiwei-Feng committed Jun 24, 2021
1 parent 2afad6f commit 7db4f1b
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Miscellaneous/randomize-quick-sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package Miscellaneous

import (
"math/rand"
"time"
)

//
// coverage time complexity: O(n), worst O(n^2)
// space complexity: O(n)
//
func findKthSmallestNumberUsingRandomQuickSort(nums []int, k int) int {
if k > len(nums) {
return -1
}
return recursiveFindPivot(nums, k, 0, len(nums)-1)
}

func recursiveFindPivot(nums []int, k, start, end int) int {
p := partitionRandomized(nums, start, end)
if p == k-1 {
return nums[p]
}
if p > k-1 {
return recursiveFindPivot(nums, k, start, p-1)
}
return recursiveFindPivot(nums, k, p+1, end)
}

func partitionRandomized(nums []int, low, high int) int {
if low == high {
return low
}

rand.Seed(time.Now().Unix())
pivot_ind := low + rand.Intn(high-low)
nums[pivot_ind], nums[high] = nums[high], nums[pivot_ind]

pivot := nums[high]
i := low - 1
for j := low; j < high; j++ {
if nums[j] < pivot {
i++
nums[i], nums[j] = nums[j], nums[i]
}
}
nums[i+1], nums[high] = nums[high], nums[i+1]
return i + 1
}
27 changes: 27 additions & 0 deletions Miscellaneous/randomize-quick-sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package Miscellaneous

import "testing"

func Test_findKthSmallestNumberUsingRandomQuickSort(t *testing.T) {
type args struct {
nums []int
k int
}
tests := []struct {
name string
args args
want int
}{
{"case1", args{[]int{1, 5, 12, 2, 11, 5}, 3}, 5},
{"case2", args{[]int{1, 5, 12, 2, 11, 5}, 4}, 5},
{"case3", args{[]int{5, 12, 11, -1, 12}, 3}, 11},
{"case4", args{[]int{5, 12, 11, -1, 12}, 6}, -1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := findKthSmallestNumberUsingRandomQuickSort(tt.args.nums, tt.args.k); got != tt.want {
t.Errorf("findKthSmallestNumberUsingRandomQuickSort() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 7db4f1b

Please sign in to comment.