Last active
August 29, 2015 14:08
-
-
Save longbuilder/30399c09310e34c76866 to your computer and use it in GitHub Desktop.
sort
This file contains hidden or 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
#ifndef BUBBLE_SORT_H_ | |
#define BUBBLE_SORT_H_ | |
template <typename T> | |
void swap(T &a, T &b) | |
{ | |
T tmp = a; | |
a = b; | |
b = tmp; | |
} | |
template <typename T> | |
void bubble_sort(T *A, int low, int high) | |
{ | |
int last; | |
while(low + 1 < high) | |
{ | |
last = -1; | |
for (int i = low + 1; i < high; ++i) | |
{ | |
if (A[i] < A[i-1]) | |
{ | |
swap(A[i], A[i-1]); | |
last = i; | |
} | |
} | |
high = last; | |
} | |
} | |
#endif |
This file contains hidden or 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
#ifndef MERGE_SORT_H_ | |
#define MERGE_SORT_H_ | |
template <typename T> | |
void merge(T *a, int low, int mid, int high, T *tmpbuf) | |
{ | |
int i = low; | |
int j = mid; | |
int k = 0; | |
while( i < mid && j < high) | |
{ | |
if (a[i] <= a[j]) | |
tmpbuf[k++] = a[i++]; | |
else | |
tmpbuf[k++] = a[j++]; | |
} | |
while (i < mid) tmpbuf[k++] = a[i++]; | |
while (j < high) tmpbuf[k++] = a[j++]; | |
for (int i = low; i < high; ++i) | |
{ | |
a[i] = tmpbuf[i - low]; | |
} | |
} | |
template <typename T> | |
void merge_sort(T *A, int low, int high, T* tmpbuf) | |
{ | |
if (high - low < 2) return; | |
int mid = (low + high) / 2; | |
merge_sort(A, low, mid, tmpbuf); | |
merge_sort(A, mid, high, tmpbuf); | |
merge(A, low, mid, high, tmpbuf); | |
} | |
template <typename T> | |
void merge_sort(T *A, int low, int high) | |
{ | |
if (high - low < 0) return; | |
T *tmpbuf = new T[high - low]; | |
merge_sort(A, low, high, tmpbuf); | |
delete []tmpbuf; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment