#include <iostream>
#include <windows.h>
using namespace std;
#define MERGE_SORT
void BubbleSort(int a[], int n)
{
for (int i=n-1;i>0;i--)
{
for (int j=0;j<i;j++)
{
if (a[j]>a[j+1])
swap(a[j],a[j+1]);
}
}
}
void InsertSort(int a[], int n)
{
for (int i=1;i<n;i++)
{
int j=i-1;
int temp=a[i];
while (j>=0&&a[j]>temp)
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
void SeleteSort(int a[], int n)
{
for (int i=n-1;i>0;i--)
{
int max=i;
for (int j=0;j<i;j++)
{
if (a[j]>a[max])
max=j;
}
swap(a[max],a[i]);
}
}
void QuickSort(int a[], int left, int right)
{
if (left<right)
{
int i=left, j=right, temp=a[i];
while (i<j)
{
while (i<j&&a[j]>=temp)
j--;
if (i<j)
a[i++]=a[j];
while (i<j&&a[i]<=temp)
i++;
if (i<j)
a[j--]=a[i];
}
a[i]=temp;
QuickSort(a,left,i-1);
QuickSort(a,i+1,right);
}
}
void ShellSort(int a[], int n)
{
int i,j,gap;
for (gap=n/2;gap>0;gap/=2)
{
for (i=0;i<gap;i++)
{
for (j=i+gap;j<n;j+=gap)
{
if (a[j-gap]>a[j])
{
int k=j-gap;
int temp=a[j];
while (k>=0&&a[k]>temp)
{
a[k+gap]=a[k];
k-=gap;
}
a[k+gap]=temp;
}
}
}
}
}
#ifdef MERGE_SORT
void MergeArray(int a[],int start, int mid, int end, int temp[])
{
int i=start, j=mid+1;
int m=mid, n=end;
int k=0;
while (i<=m&&j<=n)
{
if (a[i]>=a[j])
temp[k++]=a[j++];
else
temp[k++]=a[i++];
}
while (i<=m)
temp[k++]=a[i++];
while (j<=end)
temp[k++]=a[j++];
for (i=0;i<k;i++)
a[i+start]=temp[i];
}
void IMergeSort(int a[],int start, int end, int temp[])
{
if (start<end)
{
int mid=(start+end)/2;
IMergeSort(a,start,mid,temp);
IMergeSort(a,mid+1,end,temp);
MergeArray(a,start,mid,end,temp);
}
}
bool MergeSort(int a[], int n)
{
int* temp=new int[n];
if (!temp)
return false;
IMergeSort(a,0,n-1,temp);
delete[] temp;
return true;
}
#endif
void HeapSort(int a[], int n)
{
}
void main()
{
int a[10]={7,3,9,0,1,8,2,4,6,5};
//BubbleSort(a,10);
//InsertSort(a,10);
//SeleteSort(a,10);
//QuickSort(a,0,9);
//ShellSort(a,10);
MergeSort(a,10);
for (int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
}排序算法C++实现
最新推荐文章于 2025-03-04 21:39:02 发布
3071

被折叠的 条评论
为什么被折叠?



