排序算法代码如下:
void Sort_Algorithm::Bubble_Sort(int* &nums, const int len)
{
bool haschange = true;
for(int i=0; i<len && haschange; i++) {
haschange = false;
for(int j=1; j<len-i; j++) {
if(nums[j-1] > nums[j]) {
int t = nums[j-1];
nums[j-1] = nums[j];
nums[j] = t;
haschange = true;
}
}
}
}
void Sort_Algorithm::Insertion_Sort(int* &nums, const int len)
{
for(int j, i=1; i<len; i++) {
int current = nums[i];
for(j=i-1; j>0 && nums[j]>current; j--) {
nums[j+1] = nums[j];
}
nums[j+1] = current;
}
}
void Sort_Algorithm::Merge_Sort(int* &nums, const int low, const int high)
{
if(low > high) return;
int middle = low + (high - low)/2;
Merge_Sort(nums, low, middle);
Merge_Sort(nums, middle, high);
Merge(nums, low, middle, high);
}
void Sort_Algorithm::Merge(int* &nums, const int low, const int middle, const int high)
{
int nums_copy[500];
for(int i=low; i<=high; i++) {
nums_copy[i] = nums[i];
}
int k = low, i = low, j = middle+1;
while(k <= high) {
if(i > middle) nums[k++] = nums_copy[j++];
else if(j > high) nums[k++] = nums_copy[i++];
if(nums_copy[j] < nums_copy[i]) nums[k++] = nums_copy[j++];
else nums[k++] = nums_copy[i++];
}
}
void Sort_Algorithm::Quick_Sort(int* &nums, const int low, const int high)
{
if(low >= high) return;
int p = partition(nums, low, high);
Quick_Sort(nums, low, p);
Quick_Sort(nums, p, high);
}
int Sort_Algorithm::partition(int* &nums, const int low, const int high)
{
int middle = low + (high - low)/2;
Swap(nums, middle, high);
int i, j;
for(int i=low,j=low; j<high; j++) {
if(nums[j] < nums[high]) {
Swap(nums, i++, j);
}
}
Swap(nums, i, high);
return i;
}
template<typename T>
void Swap(T* &nums, const T i, const T j)
{
T a = nums[i];
nums[i] = nums[j];
nums[j] = a;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)