zoukankan      html  css  js  c++  java
  • 堆的建立,插入和自动排序

    在网上看的代码基本上都是这样的:

    #include<iostream>
    using namespace std;
    
    void MakeHeap (int a[], int n);
    
    int
    main ()
    {
      int a[100];
      int n, i;
    
      cout << "Enter the number:" << endl;
      cin >> n;
    
      for (i = 1; i <= n; i++)
        {
          cout << "Enter the element of the Heap:" << endl;
          cin >> a[i];
        }
    
      MakeHeap (a, n);
    
      cout << "The Heap is:" << endl;
      for (i = 1; i <= n; i++)
        {
          cout << a[i] << " ";
        }
    
      cout << endl;
    
      return 1;
    }
    
    void
    MakeHeap (int a[], int n)
    {
      int i, j, flag;
    
      for (i = n / 2; i >= 1; i--)
        {
          j = 2 * i;
          if (a[j] <= a[j + 1])
        j++;
          if (a[i] < a[j])
        {
          flag = a[i];
          a[i] = a[j];
          a[j] = flag;
        }
        }
    }
    



    但是我总感觉不太对,所以就拿这个运行了一下,结果真的是错的,他这里只是实现了一步而已。也许是我没搞明白他的意思吧。

    所以我自己实现了一个简单的,没考虑算法复杂度(特别是堆的建立,堆的排序还是挺简单的)。

    #include<iostream>
    using namespace std;
    
    int data[100];
    int count;
    void printList(int data[],int length)
    {
    	int i;
    	for(i=0;i<length;i++)
    	{
    		cout<<data[i]<<" ";
    	}
    	cout<<endl;
    }
    
    void swap(int& first,int& second )
    {
    	int temp=first;
    	first=second;
    	second=temp;
    }
    
    void HeapSort(int* data,int position)
    {
    	if(position<=0)
    		return;
    	if(data[position]>data[(position-1)/2])
    	{
    		swap(data[position],data[(position-1)/2]);
    		HeapSort(data,(position-1)/2);
    	}
    }
    
    void insert(int* data,int value)
    {
    	data[count++]=value;
    	HeapSort(data,count-1);
    }
    
    void BuildBigHeap(int* data,int size)
    {
    	bool isChange=true;
    	while(isChange)
    	{
    		isChange=false;
    		int i;
    		for(i=(size-2)/2;i>=0;i--)
    		{
    			int j=2*i+1;
    			if(data[j]<data[j+1])
    				j++;
    			if(data[i]<data[j])
    			{
    				swap(data[i],data[j]);
    				isChange=true;
    			}
    		}
    	}	
    }
    void main()
    {	
    	cout<<"请输入count的值:";
    	cin>>count;
    	cout<<endl;
    	int i;
    	for(i=0;i<count;i++)
    	{
    		cout<<"请输入第"<<i<<"个值: ";
    		cin>>data[i];
    		cout<<endl;
    	}
    	printList(data,count);
    
    	BuildBigHeap(data,count);
    	printList(data,count);
    
    	insert(data,7);
    	printList(data,count);
    	return;
    }
    



  • 相关阅读:
    136. 只出现一次的数字
    Eclipse Git Pull报 cannot open git-upload-pack错误的解决方案
    数据结构和算法1 稀疏数组
    Netty学习二 TCP粘包拆包以及Netty解决TCP粘包拆包
    Java值传递和引用传递
    Git命令教程
    Properties文件载入工具类
    有序的properties的工具类
    对象操作工具类
    反射工具类
  • 原文地址:https://www.cnblogs.com/james1207/p/3297354.html
Copyright © 2011-2022 走看看