-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
show how many nos. are smaller than current no.
- Loading branch information
Nishi Davidson
authored and
Nishi Davidson
committed
Mar 27, 2020
1 parent
32116da
commit 00261db
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
) | ||
|
||
func main() { | ||
|
||
nums := []int{8,1,2,3,2,4} | ||
//sort the list with O(nlog(n)) | ||
nums_sorted := MergeSort(nums) | ||
|
||
fmt.Printf("Sorted list:%d\n", nums_sorted) | ||
fmt.Println() | ||
|
||
m := make(map[int]int) | ||
for i:=0; i<len(nums_sorted); i++ { | ||
_, ok := m[nums_sorted[i]] | ||
if ok == false { | ||
m[nums_sorted[i]] = i | ||
} else { | ||
m[nums_sorted[i]] = m[nums_sorted[i]] | ||
} | ||
} | ||
|
||
nums_out := []int{} | ||
for i:=0; i<len(nums); i++ { | ||
nums_out = append(nums_out, m[nums[i]]) | ||
} | ||
|
||
fmt.Printf("Numbers in the current array: %d \n", nums) | ||
fmt.Println() | ||
fmt.Printf("Numbers smaller than current no: %d \n", nums_out) | ||
|
||
} | ||
|
||
func MergeSort(s []int) []int { | ||
if len(s) <= 1 { | ||
return s | ||
} | ||
n := len(s)/2 | ||
l := MergeSort(s[:n]) | ||
r := MergeSort(s[n:]) | ||
|
||
return Merge(l, r) | ||
} | ||
|
||
func Merge(l, r []int) []int { | ||
ret := []int {} | ||
for len(l) > 0 || len(r) > 0 { | ||
if len(l) == 0 { | ||
return append(ret, r...) | ||
} | ||
if len(r) == 0 { | ||
return append(ret, l...) | ||
} | ||
if l[0] < r[0] { | ||
ret = append(ret, l[0]) | ||
l = l[1:] | ||
} else { | ||
ret = append(ret, r[0]) | ||
r = r[1:] | ||
} | ||
} | ||
return ret | ||
} |