• 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);
    	}
    }
    
    
    
  • 相关阅读:
    java soket 和nio
    面试题中问到 aop di ioc 怎么回答
    细谈hashmap
    java中length和length()还有size()的区别
    MySQL 中实现可重复读(RR)的原理--MVCC
    关于字节流/字符流操作文件的问题
    MySQL 中索引优化(即避免索引失效)
    MySQL 数据库中索引的实现 和 建立索引的原则
    CAS和ABA问题
    Volatile的简单理解
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812000.html
Copyright © 2020-2023  润新知