• A1098 Insertion or Heap Sort [堆排序]


    在这里插入图片描述
    堆排序,先不断向下调整建最大堆,然后堆排序

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<stack>
    #include<string>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    
    bool judge(int a[], int b[], int n)
    {
    	for (int i = 1; i <= n; i++)
    	{
    		if (a[i] != b[i])
    			return false;
    	}
    	return true;
    }
    
    bool insert_sort(int a[],int b[],int n)
    {
    	int i, j;
    	for (i = 2; i <=n; i++)
    	{
    		int temp = a[i];
    		for (j = i; j - 1 >= 1 && temp < a[j - 1];j--)
    		{
    			a[j] = a[j - 1];
    		}
    		a[j] = temp;
    		if (judge(a, b, n))
    		{
    			i++;
    			int temp = a[i];
    			for (j = i; j - 1 >= 1 && temp < a[j - 1]; j--)
    			{
    				a[j] = a[j - 1];
    			}
    			a[j] = temp;
    			return true;
    		}
    	}
    	return false;
    }
    
    void downAdjust(int low, int high,int a[])
    {
    	int i = low, j = i * 2;
    	while (j <= high)
    	{
    		if (j + 1 <= high && a[j + 1] > a[j])
    			j = j + 1;
    		if (a[j] > a[i])
    		{
    			swap(a[j], a[i]);
    			i = j;
    			j = i * 2;
    		}
    		else
    			break;
    	}
    }
    
    bool heap_sort(int a[], int b[], int n)
    {
    	for (int i = n / 2; i >= 1; i--)
    	{
    		downAdjust(i, n, a);
    	}
    	for (int i = n; i > 1; i--)
    	{
    		swap(a[i], a[1]);
    		downAdjust(1, i - 1, a);
    		if (judge(a, b, n))
    		{
    			i--;
    			swap(a[i], a[1]);
    			downAdjust(1, i - 1, a);
    			return true;
    		}
    	}
    	return false;
    }
    
    void showarray(int a[], int n)
    {
    	for (int i = 1; i <= n; i++)
    	{
    		cout << a[i];
    		if (i < n) cout << " ";
    	}
    }
    
    int main()
    {
    	int n; int a[101], b[101], c[101];
    	cin >> n;
    	for (int i = 1; i <= n; i++)
    	{
    		cin >> a[i];
    		b[i] = a[i];
    	}
    	for (int i = 1; i <= n; i++)
    	{
    		cin >> c[i];
    	}
    	if (insert_sort(b, c, n))
    	{
    		cout << "Insertion Sort" << endl;
    		showarray(b, n);
    	}
    	if(heap_sort(a,c,n))
    	{
    		cout << "Heap Sort" << endl;
    		showarray(a, n);
    	}
    }
    
    
    
  • 相关阅读:
    zTree根据json选中节点,并且设置其他节点不可选
    点击一次按钮,发生多次ajax请求
    sublimeText3 中配置sass环境,并将编译后文件保存到指定文件夹
    MD5加密
    c# Http请求之HttpClient
    xml与object 之间的ORM
    wpf和winform的那点区别
    c# http请求ajax页面
    c# https请求
    python爬虫框架Pyspider初次接触
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812000.html
Copyright © 2020-2023  润新知