数据结构和算法总结（二）：排序

1.冒泡排序

void bubbleSort(vector<int>& num)
{
for(int i = num.size()- 1;i > 0;i--)
{
for(int j = 1;j <= i;j++)
{
if(num[j] < num[j-1])
swap(num[j],num[j-1]);
}
}
}

//提前终止的冒泡排序
bool PreStopBubble(vector<int>& num,const int n)
{
bool isSwapped = false;
for(int i = 1;i < n;i++)
{
if(num[i - 1] > num[i])
{
isSwapped = true;
cout << "Swapped!" << endl;
swap(num[i - 1],num[i]);
}
}
return isSwapped;
}

void PreStopBubbleSort(vector<int>&num)
{
for(int i = num.size();i > 0 && PreStopBubble(num,i);i--);
//如果某一次冒泡过程未发生交换，那么说明数组已经有序，所以提前终止
}

2.选择排序

void SelectionSort(vector<int>& num)
{
for(int i = num.size();i > 0 ;i--)
{
int tmp = num[0],index = 0;
for(int j = 1;j < i;j++)
{
if(num[j] > tmp)
{
tmp = num[j];
index = j;
}
}
swap(num[index],num[i - 1]);
}
}

3.计数排序

void CountSort(vector<int>& num,const int maxnum)
{
vector<int> countBox(maxnum + 1,0);
for(int i =0;i < num.size();i++)
{
countBox[num[i]]++;
}
int j = 0;
for(int i = 0;i < num.size();i++)
{
if(countBox[j]-- > 0)
num[i] = j;
else
{
j++;i--;
}
}
}

4.归并排序

void MergeArray(vector<int>& num,int left,int right,int mid,vector<int>& tmp)
{ //合并两个有序子数组
int l = left,lm = mid;
int mr = mid + 1,r = right;
int k = 0;
while(l <= lm && mr <= r)
{
if(num[l] < num[mr])
tmp[k++] = num[l++];
else
tmp[k++] = num[mr++];
}
while(l <= lm) tmp[k++] = num[l++];
while(mr <= r) tmp[k++] = num[mr++];
for(int i = 0;i < k;i++)
{
num[left + i] = tmp[i];
}
}

void MergeSort(vector<int>& num,int left,int right,vector<int>& tmp)
{
if(left >= right)
return;
int mid = (left + right)/2;
//递归+分治
MergeSort(num,left,mid,tmp);
MergeSort(num,mid + 1,right,tmp);
MergeArray(num,left,right,mid,tmp);
}

void MergeSort_begin(vector<int>& num) //归并排序入口
{
if(num.empty())
return ;
vector<int> tmp(num.size());
MergeSort(num,0,num.size() - 1,tmp);
}


5.快速排序

int qs_partition(vector<int>& num,int left,int right)
{
int pivot = num[left];
int l = left,r =right;
while(l < r)
{
while(l < r && num[r] >= pivot) r--;
if(l < r)
num[l++] = num[r];
while(l < r && num[l] < pivot) l++;
if(l < r)
num[r--] = num[l];
}
num[l] = pivot;
return l;
}

void quickSort(vector<int>& num,int left,int right)
{
if(left > right)
return;
int k = qs_partition(num,left,right);
quickSort(num,left,k - 1);
quickSort(num,k + 1,right);
}


int qs_partition(vector<int>& num,int left,int right)
{
int pivot = num[left];
int l = left,r =right;
while(l < r)
{
while(l < r && num[r] >= pivot) r--;
if(l < r)
num[l++] = num[r];
while(l < r && num[l] < pivot) l++;
if(l < r)
num[r--] = num[l];
}
num[l] = pivot;
return l;
}

void stack_quickSort(vector<int>& num)
{
int left = 0,right = num.size() - 1;
if(left > right)
return;
stack<int> stk;
int l,r;
stk.push(right);
stk.push(left);
while(!stk.empty())
{
l = stk.top();stk.pop();
r = stk.top();stk.pop();
if(l < r)
{
int k = qs_partition(num,l,r);
stk.push(k - 1);stk.push(l);
stk.push(r);stk.push(k + 1);
}
}
}


《数据结构、算法与应用——C++描述》   作者：【美】 萨特吉·萨尼       机械工业出版社

posted @ 2018-03-18 17:01  0kk470  阅读(483)  评论(0编辑  收藏  举报