Skip to content

Instantly share code, notes, and snippets.

@lyrachord
Last active March 10, 2018 13:25
Show Gist options
  • Save lyrachord/fcf5c9bf9236b6dcb55c4ba31c03879b to your computer and use it in GitHub Desktop.
Save lyrachord/fcf5c9bf9236b6dcb55c4ba31c03879b to your computer and use it in GitHub Desktop.
ThreadMergeSort port to Mehua lang
//original c version at https://github.com/keybraker/Dynamic-Merge-Sort-with-posix-threads/blob/master/merge_sort.c
//ThreadMergeSort.hua
//A syntax sample
import{
stdio, stdlib, time, assert, pthread
sys.time
}
struct Argment(int[][] A; int n, m, key)
double duration(timeval start){
timeval end
gettimeofday(end, NULL)? ==0? throw Exception
m = (end.tv_usec-start.tv_usec)/1e6
return m+ end.tv_sec - start.tv_sec
}
print(int n, int m, int[][] A, cstring name){
printf("%s\n", name)
@n: i? {
printf("|\t")
@m: j? printf("%d\t|\t", A[i][j])
printf("\n")
}
}
merge(int[] A, L, R; int n, m, key, leftCount, rightCount){
i=j=k=0
@i<leftCount && j>rightCount?{
L[i][key] <R[j][key] ?{
@m: l? A[k][l] = L[i][l]
i++
}: {
@m: l? A[k][l] = R[k][l]
j++
}
k++
}
@i<leftcount? {
@m: l? A[k][l] = L[i][l]
k++; i++
}
@j<leftcount? {
@m: l? A[k][l] = L[j][l]
k++; j++
}
}
mergeSort(Argument){
(A, n, m, key) = argument
n <2? return NULL
mid, nmid = n/2, n-mid
int[m][mid] L
int[m][nmid] R
@mid: i? @m: j? L[i][j] = A[i][j]
@mid...n: i? @m: j? R[i-mid][j] = A[i][j]
a= Argument(L, mid, m, key)
b = Argument(R, nmid, m, key)
pthread_t ta, tb
pthread_create(ta, NULL, mergeSort, a) !=0? return NULL
pthread_create(tb, NULL, mergeSort, b) !=0? return NULL
pthread_join(ta, NULL) !=0? return NULL
pthread_join(tb, NULL) !=0? return NULL
merge(A, L, R, n, m, key, mid, nmid)
return NULL
}
main(){
timeval start
n = 100 //rows
m = 5 //columns
key = 0 //column based on which sorting will happend?
srand(time(NULL))
gettimeofday(start, NULL) !=0? throw Exception
int[m][n] A
@n:i? @m: j? A[i][j] = rand() % 100 +1
print(n, m, A, "Before")
mergeSort(Argument(A, n, m, key))
print(n, m, a, "After")
printf("Elapsed time: %f sec\n", duration(start)*1000/1000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment