class Sort
{
public:
Sort(void);
~Sort(void);
public:
inline void Swap(int &a,int &b);
//冒泡排序
void BubbleSort(int a[],int n);
//直接插入排序
void InsertSort(int a[],int n);
//希尔排序
void SellSort(int a[],int n);
//直接选择排序
void SelectSort(int a[],int n);
//归并排序
bool MergeSort(int a[],int n);
void mergesort(int a[],int first,int last,int temp[]);
void mergearray(int a[],int first,int mid,int last,int temp[]);
//快速排序
void QuickSort(int a[],int l,int r);
};
#include "Sort.h"
#include <stdio.h>
Sort::Sort(void)
{
}
Sort::~Sort(void)
{
}
//交换两个数
inline void Sort::Swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
//冒泡排序
//1.比较相邻的前后两个数据,如果前面的数据大于后面的数据,就将两个数据交换。
//2.这样对数组的第0个数据到n-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第n-1个位置。
//3.n=n-1,如果n不为0就重复前面两步,否则排序完成。
void Sort::BubbleSort(int a[],int n)
{
int i,j;
for (i=0;i<n;i++)
{
for (j=1;j<n-i;j++)
{
if (a[j-1]>a[j])
{
Swap(a[j-1],a[j]);
}
}
}
}
//直接插入排序
//1.初始时,a[0]自成1个有序区,无序区为a[1...n-1],令i=1
//2.将a[i]并入当前的有序区a[0...i-1]中形成a[0...i]的有序区
//3.i++并重复第二步直到i==n-1,排序完成
void Sort::InsertSort(int a[],int n)
{
int i,j,temp;
for (i=1;i<n;i++)
{
if (a[i]<a[i-1])
{
temp=a[i];
for (j=i-1;j>=0 && a[j]>temp;j--)
{
a[j+1]=a[j];
}
a[j+1]=temp;
}
}
}
//希尔排序
//先将整个待排序元素序列分割成若干个子序列分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序时(增量足够小)时,再对全体元素进行一次直接插入排序。
void Sort::SellSort(int a[],int n)
{
int i,j,gap;
for (gap=n/2;gap>0;gap/=2)
{
for (i=gap;i<n;i++)
{
for (j=i-gap;j>=0 && a[j]>a[j+gap];j-=gap)
{
Swap(a[j],a[j+gap]);
}
}
}
}
//选择排序法
//1.初始时,数组全为无序区,令i=0
//2.在无序区中选一个最小的元素,将其与a[i]交换。交换之后a[0...i]就成了一个有序区
//3.i++,并重复第二步知道i==n-1,完成排序
void Sort::SelectSort(int a[],int n)
{
int i,j,MinIndex;
for (i=0;i<n;i++)
{
MinIndex=i;
for (j=i+1;j<n;j++)
{
if (a[j]<a[MinIndex])
{
MinIndex=j;
}
}
Swap(a[i],a[MinIndex]);
}
}
//归并排序
bool Sort::MergeSort(int a[],int n)
{
int *p=new int[n];
if (p==NULL)
{
return false;
}
mergesort(a,0,n-1,p);
delete[] p;
return true;
}
void Sort::mergesort(int a[],int first,int last,int temp[])
{
if (first<last)
{
int mid=(first+last)/2;
mergesort(a,first,mid,temp);//左边有序
mergesort(a,mid+1,last,temp);//右边有序
mergearray(a,first,mid,last,temp);//再将两个有序数列合并
}
}
void Sort::mergearray(int a[],int first,int mid,int last,int temp[])
{
int i=first,j=mid+1;
int m=mid,n=last;
int k=0;
while(i<=m && j<=n)
{
if (a[i]<a[j])
{
temp[k++]=a[i++];
}
else
temp[k++]=a[j++];
}
while(i<=m)
temp[k++]=a[i++];
while(j<=n)
temp[k++]=a[j++];
for (i=0;i<k;i++)
{
a[first+i]=temp[i];
}
}
//快速排序
void Sort::QuickSort(int a[],int l,int r)
{
if (l<r)
{
int i=l,j=r,x=a[l];
while(i<j)
{
while(i<j && a[j]>x)
j--;
if (i<j)
a[i++]=a[j];
while(i<j && a[i]<x)
i++;
if (i<j)
a[j--]=a[i];
}
a[i]=x;//此时i=j
QuickSort(a,l,i-1);//递归调用
QuickSort(a,i+1,r);
}
}