zoukankan      html  css  js  c++  java
  • 堆排序(代码1)

    #include <stdio.h>
    #include <stdlib.h>
    
    void build_heap(int data[], int);
    void adjust_heap(int data[], int);
    void heap_sort(int data[], int);
    int sub_max_heap(int data[], int, int);
    
    int main(int argc, char *argv[])
    {
    	int i;
    	int data[12] = {6, 10, 3, 5, 12, 8, 4, 23, 1, 2, 9, 7 };
    
    	heap_sort(data, 12);
    
    	for (i = 0; i < 12; ++i)
    	{
    		printf("%d ", data[i]);
    	}
    
    	printf("
    ");
    	return 0;
    }
    
    void heap_sort(int data[], int num)
    {
    	int i = 1;
    	build_heap(data, num);
    
    	for (i = 1; i < num; ++i)
    	{
    		int temp;
    		temp = data[0];
    		data[0] = data[num - i];
    		data[num - i] = temp;
    
    		adjust_heap(data, num - i);	
    	}
    
    }
    
    
    void build_heap(int data[], int num)
    {
    	int i, k, p;
    
    	for (i = num / 2 - 1; i >= 0; --i)
    	{
    		k = sub_max_heap(data, num, i);
    
    		while (2 * k + 1 < num)
    		{
    			p = k;
    			k = sub_max_heap(data, num, p);
    		}
    	}
    
    }
    
    
    void adjust_heap(int data[], int num)
    {
    	int temp;
    	int k, p;
    
    	k = 0;
    	while(2 * k + 1 < num)
    	{
    		p = k;
    		k = sub_max_heap(data, num, p);
    	}
    
    
    }
    
    int sub_max_heap(int data[], int num, int i)
    {
    	int k;
    
    	if (2 * i + 2 <= num - 1 && data[2 * i + 1] > data[2 * i + 2])
    		k = 2 * i + 1;
    	else if (2 * i + 2 <= num - 1)
    		k = 2 * i + 2;
    	else
    		k = 2 * i + 1;
    
    	if (data[k] > data[i])
    	{
    		int temp;
    		temp = data[k];
    		data[k] = data[i];
    		data[i] = temp;
    	}
    	
    	return k;
    
    }
    /*
    int sub_max_heap(int data[], int num, int i)
    {
    	int largest;
    	int l, r;
    
    	l = 2 * i + 1;
    	r = 2 * i + 2;
    	
    	if (l <= num - 1 && data[l] > data[i])
    		largest = l;
    	else
    		largest = i;
    	
    	if (r <= num - 1 && data[r] > data[largest])
    		largest = r;
    	if (largest != i)
    	{
    		int temp;
    		temp = data[i];
    		data[i] = data[largest];
    		data[largest] = temp;
    	}
    
    	return largest;
    }
    
    
    
    
    */
    
  • 相关阅读:
    获取指定<文字行数>的<高度>是多少 TextKit
    JS 与 OC 交互
    PHP-note
    MySQL函数
    freeSWITCH之多平台测试通信
    freeSWITCH之安装
    PHP面向对象
    MySQL Optimization 优化原理
    理解常量指针与指针常量?
    InterView之PHP(2)
  • 原文地址:https://www.cnblogs.com/yyxayz/p/3997957.html
Copyright © 2011-2022 走看看