http://blog.youkuaiyun.com/fengzhitalker/article/details/7898804
无疑这种方法比本来的方法更加快捷,减少了内存开销,直接在原数组进行排序
#include <iostream>
using namespace std;
//采用挖坑法实现快速排序
template <typename T>
int quickSort2(T *const t, const int begin,const int end)
{
if(begin >= end)
{
return 0;
}
T temp = t[begin];
int left = begin;
int right = end;
while(left < right)
{
while(t[right] > temp && left < right)
{
right--;
}
if(left != right)
{
t[left] = t[right];
left++;
}
while(t[left] < temp && left < right)
{
left++;
}
if(left != right)
{
t[right] = t[left];
right--;
}
}
t[left] = temp;
//对确定好位置的元素的左右子数组进行排序
quickSort2(t, begin, left - 1);
quickSort2(t, left + 1, end);
}
template <typename T>
int printArray(T *const t, int len)
{
for(int i = 0; i < len; i++)
{
cout << t[i] << ';';
}
cout<<endl;
}
int main(int argc, char *argv[])
{
int c[10] = {9,4,6,1,11,4,5,3,10,0};
quickSort2(c, 0, sizeof(c)/sizeof(int) - 1);
printArray(c, sizeof(c)/sizeof(int));
return 0;
}
----------------------------------------------
冒泡排序和插入排序
#include <iostream>
using namespace std;
template <typename T>
//冒泡排序
int bubbleSort(T *const t, int len)
{
for(int i = len - 1; i > 0; i--)
{
for(int j = 0 ; j < i; j++)
{
if(t[j] > t[j + 1])
{
T temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
}
}
}
return 0;
}
//插入排序
template <typename T>
int insertSort(T *const t, int len)
{
for(int i = 1; i < len; i++)
{
for(int j = i; j >= 1; j--)
{
if(t[j] < t[j - 1])
{
T temp = t[j - 1];
t[j - 1] = t[j];
t[j] = temp;
}else
{
break;
}
}
}
}
template <typename T>
int printArray(T *const t, int len)
{
for(int i = 0; i < len; i++)
{
cout << t[i] << ';';
}
cout<<endl;
}
int main(int argc, char *argv[])
{
int c[10] = {9,4,7,6,11,4,3,2,1,0};
// bubbleSort(c, sizeof(c)/sizeof(int));
insertSort(c, sizeof(c)/sizeof(int));
printArray(c, sizeof(c)/sizeof(int));
return 0;
}