插入排序
分析
- 当数组有序时,插入排序性能最佳,但是当为逆序时,插入排序性能最差;
- 使用内存空间少,几乎相当于一个同类型的数据大小;
- 性能是平方级别,每个元素的平均移动距离是n/3;
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000;
int a[maxn];
void Insert(int a[],int p,int v)
{
int now = p - 1;
while(now >= 0 && a[now] > v)
a[now + 1] = a[now--];
a[now + 1] = v;
}
void Sort(int a[],int num)
{
for(int i = 1; i < num ; i++)
{
Insert(a,i,a[i]);
}
}
int main()
{
int T;
cin >> T;
while(T--)
{
int num;
cin >> num;
for(int i = 0; i < num ;i++)
{
cin >> a[i];
}
Sort(a,num);
for(int i = 0; i < num;i++)
{
cout << a[i] << " ";
}
cout << endl;
}
return 0;
}
选择排序
分析
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000;
int a[maxn];
void Sort(int a[],int& now)
{
if(now < 0)
return;
int p = 0,v = a[0];
for(int i = 0;i <= now; i++)
{
if(v < a[i])
{
p = i,v = a[i];
}
}
swap(a[p],a[now]);
now -= 1;
Sort(a,now);
}
int main()
{
int T;
cin >> T;
while(T--)
{
int num;
cin >> num;
for(int i = 0; i < num ;i++)
{
cin >> a[i];
}
int snum = num - 1;
Sort(a,snum);
for(int i = 0; i < num;i++)
{
cout << a[i] << " ";
}
cout << endl;
}
return 0;
}
快速排序
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000;
int a[maxn];
int num;
void P(int a[])
{
for(int i = 1;i <= num; i++)
{
cout << a[i] << ' ';
}
cout<<endl;
}
void Sort(int a[],int left,int right)
{
if(left > right)
return;
int j = right,i = left;
int v = a[left];
while(i != j)
{
while(a[j] >= v && i < j)
j--;
while(a[i] <= v && i < j)
i++;
if(i < j)
{
int t = a[i];
a[i] = a[j], a[j] = t;
}
}
a[left] = a[i], a[i] = v;
Sort(a,left,i - 1);
Sort(a,i + 1,right);
return;
}
int main()
{
int T;
cin >> T;
while(T--)
{
cin >> num;
for(int i = 1; i <= num ; i++)
{
cin >> a[i];
}
Sort(a,0,num);
for(int i = 1; i <= num; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
return 0;
}