@[TOC]第二章快速排序
#include <iostream>
#include <vector>
using namespace std;
void merge(auto& tempvector,auto& unsorted_vector,int low,int mid,int high)
{
int lowpos = low,highpos = mid+1;
for(int i=low;i<=high;++i)
tempvector[i] = unsorted_vector[i];
for(int i=low;i<=high;++i)
{
if(lowpos >= mid+1) unsorted_vector[i] = tempvector[highpos++];
else if(highpos >= high+1) unsorted_vector[i] = tempvector[lowpos++];
else if(tempvector[lowpos] <= tempvector[highpos]) unsorted_vector[i] = tempvector[lowpos++];
else unsorted_vector[i] = unsorted_vector[i] = tempvector[highpos++];
}
}
void Shell_Sort(auto& tempvector,auto& unsorted_vector,int left,int right)
{
if(left>=right) return;
int mid = left + (right - left)/2;
Shell_Sort(tempvector,unsorted_vector,left,mid);
Shell_Sort(tempvector,unsorted_vector,mid+1,right);
merge(tempvector,unsorted_vector,left,mid,right);
}
void Sort(auto& unsorted_vector)
{
int size = unsorted_vector.size();
vector<int> tempvector(size);
Shell_Sort(tempvector,unsorted_vector,0,size-1);
return;
}
int main()
{
int temp;
vector<int> unsorted_vector;
cout<<"please input ur unsorted_list ~ '-1' is the stop symbol"<<endl;
while(cin>>temp)
{
if(temp == -1) break;
unsorted_vector.push_back(temp);
}
Sort(unsorted_vector);
cout<<"this is the sorted_vector numbers"<<endl;
for(const auto& num:unsorted_vector)
cout<<num<<' ';
return 0;
}
输入:9181 6042 2649 9858 8310 6706 9744 6296 2779 1194 8913 798 7877 9443 5646 6998 5747 8104 5129 5090 6111 2408 1423 1557 1883 1364 7436 8217 1891 1000 -1
`输出:798 1000 1194 1364 1423 1557 1883 1891 2408 2649 2779 5090 5129 5646 5747 6042 6111 6296 6706 6998 7436 7877 8104 8217 8310 8913 9181 9443 9744 9858
@[TOC]三向切分快速排序算法
```cpp
#include <iostream>
#include <vector>
using namespace std;
void Sort(auto& unsorted_vector,int lo,int hi)
{ if(hi<=lo)return;
int It=lo,i=lo+1,gt=hi;
int c=unsorted_vector[lo];
while (i<=gt)
{
if (c>unsorted_vector[i])swap(unsorted_vector[i],unsorted_vector[It++]);
else if (c<unsorted_vector[i])swap(unsorted_vector[i],unsorted_vector[gt--]);
else i++;
}
Sort(unsorted_vector,lo,It-1);
Sort(unsorted_vector,gt+1,hi);
}
int main()
{
int temp;
vector<int> unsorted_vector;
cout<<"please input ur unsorted_list ~ '-1' is the stop symbol"<<endl;
while(cin>>temp)
{
if(temp == -1) break;
unsorted_vector.push_back(temp);
}
int lo=0;
int hi=unsorted_vector.size()-1;
Sort(unsorted_vector,lo,hi);
cout<<"this is the sorted_vector numbers"<<endl;
for(const auto& num:unsorted_vector)
cout<<num<<' ';
return 0;
}