zoukankan      html  css  js  c++  java
  • 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);
    	}
    }
    
    
    
  • 相关阅读:
    Step one : 熟悉Unix/Linux Shell 常见命令行 (三)
    Step one : 熟悉Unix/Linux Shell 常见命令行 (一)
    PLAN: step one
    PLAN : 入门题目 ( update )
    SZU : A11 Sequence
    SZU:B85 Alec's Eggs
    codeforces 518B. Tanya and Postcard 解题报告
    BestCoder8 1001.Summary(hdu 4989) 解题报告
    hdu 1556.Color the ball 解题报告
    codeforces 515C. Drazil and Factorial 解题报告
  • 原文地址:https://www.cnblogs.com/Hsiung123/p/13812000.html
Copyright © 2011-2022 走看看