博主初学者,有什么错误或不足还望指正。
快速排序
思路:取出一个数q,通过交换使其左边的数都小于它的值,右边的数的都大于它的值将原序列以q为界分成两个子序列,对左右两个子序列再次进行上述过程,直到子序列都只含一个元素。
/*
author hlx
date 2018/3/24
xmu
*/
#include <iostream>
using namespace std;
inline void swap (int a[],int i,int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//用于交换数列中的两个值
void qsort (int a[],int left,int right)
{
if (left >= right)
{
return;
}
//递归终止条件,left == right(也就是只有递归序列只有一个数)
int last = left;
swap (a,left,(left + right) / 2);
//将数列中间的数q交换到数列最左端
//12 2 46 7 5 18 46 -> 7 2 46 12 5 18 46
for (int i = left + 1;i <= right;i++)
{
if (a[i] < a[left])
{
swap (a,++last,i);//last指向比中间的那个数小的最右边的数
}
}
//7 2 46 12 5 18 46 -> 7 2 5 12 46 18 46
swap(a,left,last);
//把中间的数q换回中间,使其前面的数都小于它后面的数都大于它
//7 2 5 12 46 18 46 -> 5 2 7 12 46 18 46
qsort(a,left,last - 1);
qsort(a,last + 1,right);
//中间的数q位置不变对左右两部分做相同的操作
}
int main()
{
int a[] = {12,2,46,7,5,18,46};
int left = 0;
int right = sizeof(a) / sizeof(int) - 1;
//数列从0开始所以right为数列所含元素个数-1
qsort(a,left,right);
for (int i = left;i <=right;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
归并排序
思路:归并排序与快速排序思想类似,将原本的序列分割成若干个子序列,再合并成一个有序的序列。个人认为理解了快速排序后在理解归并排序就不再是一件困难的事情了。
/*
author hlx
date 2018/3/25
xmu
*/
#include<iostream>
#include<malloc.h>
using namespace std;
void merge (int a[],int begin,int mid,int last)
{
int begin1,begin2,end1,end2;
int size = last - begin + 1;
int *temp = (int*) malloc(sizeof(int) * size);
//申请临时空间储存两个有序子序列合并后的序列
begin1 = begin;
end1 = mid;
begin2 = mid + 1;
end2 = last;
int i = 0;
while (begin1 <= end1 && begin2 <= end2)
{
if (a[begin1] > a[begin2])
{
temp[i++] = a[begin1++];
}
else
{
temp[i++] = a[begin2++];
}
}
while (begin1 <= end1)
{
temp[i++] = a[begin1++];
}
while (begin2 <= end2)
{
temp[i++] = a[begin2++];
}
for (i = 0;i < size;i++)
{
a[i+begin] = temp[i];
}
free(temp);
}
//对子序列进行有序的合并
void mergesort(int a[],int begin,int last)
{
int mid = 0;
if (begin < last)
{
mid = (begin + last) / 2;
mergesort(a,begin,mid);
mergesort(a,mid + 1,last);
merge(a,begin,mid,last);
}
else
return;
}
//递归调用将原序列分割成若干个只含一个元素的子序列
int main()
{
int date[] = {7,56,23,2,9};
int size = sizeof(date) / sizeof(int);
mergesort(date,0,size - 1);
for (int i = 0;i < size;i++)
{
cout<<date[i]<<" ";
}
return 0;
}
用STL实现的堆排序
不是很熟悉堆的stl操作,代码看起来有点蹩脚。
/*
author hlx
date 2018/4/1
xmu
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool cmp(int x,int y)
{
return x > y;//从小到大排列用大于号,与堆的stl操作有关
}
int main()
{
vector<int> arr;//动态数组
int a[] = {5,15,9,3,7};
const int size = 5;
int i;
for (i = 0;i < size;i++)
{
arr.push_back(a[i]);
}
make_heap(arr.begin(),arr.end(),cmp);
for (i = 1;i <= size;i++)
{
cout<<arr[0]<<" ";
pop_heap(arr.begin(),arr.end(),cmp);
arr.pop_back();
}
return 0;
}