总结:
这道题始终有一个测试点过不去,是因为插入排序如 序列s为:1 3 5 7 7 2 0,这个序列前边5个都是有序的。所以第一个无序元素的时候while(s[i]<=s[i+1])有等号。。。。
1.这道题考的是给定一个序列,让你判断是堆排序还是插入排序,对于插入排序,前边为有序队列,后边为无序队列,只要找到有序队列旁边第一个无序数,就可以用sort排序,而对于堆排序,先构建最大堆,然后根和last(堆尾元素)互换,堆尾元素置为其相反数,然后判断和指定序列是否相等。思路大概是这样。
2.写完这道题,对堆排序理解更深
代码:
#include<iostream>
#include<functional>
#include<algorithm>
using namespace std;
int heapp[10000];
int heapp1[10000];
int bijiao[10000];
int n;
int last = 10000;
void swap(int &a,int&b)
{
int temp = a;
a = b; b = temp;
}
bool isR(int a[],int b[],int n)
{
bool sp = true;
for (int i = 0; i<n; i++)
{
if (a[i] != b[i]&&a[i]!=-b[i]){ sp = false; break; }
}
return sp;
}
void heapdelete(int index) //最大堆的调整
{
if (heapp[2 * index + 1]<0 && heapp[2 * index + 2]<0)return ;
else if (heapp[2 * index + 1] <0&& heapp[2 * index + 2]>=0&&heapp[index]<heapp[2*index+2]) //只有右边
{
swap(heapp[index],heapp[2*index+2]);
heapdelete(2*index+2);
}
else if (heapp[2 * index + 1]>=0 && heapp[2 * index + 2]<0&& heapp[index]<heapp[2 * index + 1]) //只有左边
{
swap(heapp[index], heapp[2 * index + 1]);
heapdelete(2*index+1);
}
else if(heapp[2*index+1]>=0&&heapp[2*index+2]>=0){ //左右都有
if (heapp[index*2+2]>heapp[2 * index + 1] && heapp[index]<heapp[2 * index + 2]) //右子树最大
{
swap(heapp[index], heapp[2 * index + 2]);
heapdelete(2 * index + 1);
heapdelete(2 * index + 2);
}
else if (heapp[index]<heapp[2 * index + 1] && heapp[2*index+1]>heapp[2 * index + 2]) //左子树最大
{
swap(heapp[index], heapp[2 * index + 1]);
heapdelete(2 * index + 1);
heapdelete(2 * index + 2);
}
else if(heapp[index]>heapp[2*index+1]&&heapp[index]>heapp[2*index+2]){ //根节点最小
heapdelete(2*index+1);
heapdelete(2*index+2);
}
}
}
int main()
{
cin >> n;
fill(heapp,heapp+10000,-1);
fill(heapp1, heapp1 + 10000, -1);
for (int i = 0; i < n; i++)
{
cin >> heapp[i];
heapp1[i] = heapp[i];
}
for (int i = 0; i < n; i++)
cin >> bijiao[i];
for (int i = n - 1; i >= 0; i--) //排列成堆
heapdelete(i);
//找堆尾
last = n - 1;
while (last>0)
{
if (isR(heapp, bijiao,n)){
cout << "Heap Sort"<<endl;
while (isR(bijiao, heapp, n)){
swap(heapp[0], heapp[last]);
heapp[last] = -heapp[last];
last--;
heapdelete(0);
}
for (int i = 0; i < n; i++)
{
if (heapp[i] < 0)heapp[i] = -heapp[i];
cout << heapp[i];
if (i != n - 1)cout << " ";
}
return 0;
}
swap(heapp[0],heapp[last]);
heapp[last] = -heapp[last];
last--;
heapdelete(0);
}
cout << "Insertion Sort" << endl;
int k = 0;
while (bijiao[k] < bijiao[k + 1])k++;
int st = 0, end = k; int temp = bijiao[k + 1];
sort(bijiao,bijiao+k+2);
for (int i = 0; i < n; i++)
{
cout << bijiao[i];
if (i != n - 1)cout << " ";
}
return 0;
}