/* bitonic.c This file contains two different implementations of the bitonic sort recursive version : recBitonicSort() imperative version : impBitonicSort() The bitonic sort is also known as Batcher Sort. For a reference of the algorithm, see the article titled Sorting networks and their applications by K. E. Batcher in 1968 The following codes take references to the codes avaiable at http://www.cag.lcs.mit.edu/streamit/results/bitonic/code/c/bitonic.c http://www.tools-of-computing.com/tc/CS/Sorts/bitonic_sort.htm http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm */ /* ------- ---------------------- Nikos Pitsianis, Duke CS ----------------------------- */ #include #include #include struct timeval startwtime, endwtime; double seq_time; int N; // data array size int *a; // data array to be sorted const int ASCENDING = 1; const int DESCENDING = 0; void init(void); void print(void); void sort(void); void test(void); inline void exchange(int i, int j); void compare(int i, int j, int dir); void bitonicMerge(int lo, int cnt, int dir); void recBitonicSort(int lo, int cnt, int dir); void impBitonicSort(void); /** the main program **/ int main(int argc, char **argv) { if (argc != 2) { printf("Usage: %s q\n where n=2^q is problem size (power of two)\n", argv[0]); exit(1); } N = 1< a[j]) agrees with the direction, then a[i] and a[j] are interchanged. **/ inline void compare(int i, int j, int dir) { if (dir==(a[i]>a[j])) exchange(i,j); } /** Procedure bitonicMerge() It recursively sorts a bitonic sequence in ascending order, if dir = ASCENDING, and in descending order otherwise. The sequence to be sorted starts at index position lo, the parameter cbt is the number of elements to be sorted. **/ void bitonicMerge(int lo, int cnt, int dir) { if (cnt>1) { int k=cnt/2; int i; for (i=lo; i1) { int k=cnt/2; recBitonicSort(lo, k, ASCENDING); recBitonicSort(lo+k, k, DESCENDING); bitonicMerge(lo, cnt, dir); } } /** function sort() Caller of recBitonicSort for sorting the entire array of length N in ASCENDING order **/ void sort() { recBitonicSort(0, N, ASCENDING); } /* imperative version of bitonic sort */ void impBitonicSort() { int i,j,k; for (k=2; k<=N; k=2*k) { for (j=k>>1; j>0; j=j>>1) { for (i=0; ii) { if ((i&k)==0 && a[i] > a[ij]) exchange(i,ij); if ((i&k)!=0 && a[i] < a[ij]) exchange(i,ij); } } } } }