Skip to content

Instantly share code, notes, and snippets.

@phlandscape
Created September 14, 2012 20:41
Show Gist options
  • Save phlandscape/3724665 to your computer and use it in GitHub Desktop.
Save phlandscape/3724665 to your computer and use it in GitHub Desktop.
this and what i wrote (@reddit)
#include <iostream>
using std::cout; using std::endl;
using std::copy;
template <typename T>
void Swap_Elements(T &a, T &b){
T temp(a); a = b; b = temp;
}
template <typename T, typename Si_ze>
void Bubble_Sort(T* arrayZ, Si_ze s){
for(Si_ze i = s; i > 0; i--){
for(Si_ze kk = 0; kk < s; kk++){
if(arrayZ[i]>arrayZ[i+1]){
Swap_Elements(arrayZ[i], arrayZ[i+1]);
}
}
}
}
template <typename T, typename Si_ze>
void Insertion_Sort(T* arrayZ, Si_ze s){
for(Si_ze i = 1; i < s; i++){
for(Si_ze kk = i; kk > 0; kk--){
if(arrayZ[kk]<arrayZ[kk-1]){
Swap_Elements(arrayZ[kk],arrayZ[kk-1]);
}else{
break;
}
}
}
}
template<typename T, typename Si_ze>
void Selection_Sort(T* arrayZ, Si_ze s){
Si_ze temp;
for(Si_ze i = 0; i < s; i++){
temp = i;
for(Si_ze kk = i; kk < s; kk++){
if(arrayZ[kk] < arrayZ[temp]){
temp = kk;
}
}
Swap_Elements(arrayZ[i], arrayZ[temp]);
}
}
template<typename T, typename Si_ze>
void Merge(T* arrayZ, Si_ze first, Si_ze second){
int i(0),j(first),k(0);
T* temp = new T[second];
while(k<second){
temp[k++] = (arrayZ[i] < arrayZ[j]) ? arrayZ[i++] : arrayZ[j++];
if(i == first){
copy(&(arrayZ[j]),&(arrayZ[second]),&(temp[k]));
break;
}
if(j == second){
copy(&(arrayZ[i]),&(arrayZ[first]),&(temp[k]));
break;
}
}
for(int m = 0; m < second; m++){
arrayZ[m] = temp[m];
}
delete temp;
}
template<typename T, typename Si_ze>
void Merge_Sort(T* arrayZ,Si_ze s){
for(int i = 1; i < s; i *= 2){
for(int kk = 0; kk < s-1; kk += 2*i){
int secondEnd = (2*i < s-kk) ? 2*i : s-kk;
Merge(&(arrayZ[kk]), i ,secondEnd);
}
}
}
int main(int argc, char** argv){
int ARRAY[] = {5,1,2,8,3,4,6};
for(int i = 0; i < 7; i++){
cout << ARRAY[i] << " ";
}
cout << endl;
Merge_Sort(ARRAY,7);
for(int i = 0; i < 7; i++){
cout << ARRAY[i] << " ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment