选择排序---简单选择排序 堆排序

一、简单选择排序

对于n个数要进行n次排序,第一次,将最小的数放在第一个。第二次,将第二小的树,放在第二个。。。。

每次都和后面的数做比較,假设是从小到大的排序,当当前的数字比后面的大时,要进行交换。


#include <stdio.h>

void chosesort(int a[],int length)
{
	int i,j,temp;
    for(i=0;i<length;i++)
		for(j=i+1;j<length;j++)
		{
			if(a[i]>a[j])
			{
			   temp = a[i];
			   a[i] = a[j];
			   a[j] = temp;
			}
		   
		}

}


void  main()
{
	int i;
	int a[] = {4,2,6,7,44,32,35,23};
	int n = 8;
	chosesort(a,n);
	for(i =0;i<n;i++)
	{
	  printf("%d ",a[i]);
	}
  
}


二、堆排序

堆是一棵全然二叉树。其每一个结点值都大于等于(小于等于)自己的左右孩子。

把一个数量为n的数组,构成堆,则其根结点为最大值(最小值),然后再对剩下的n-1个数构成堆,继续取出其根结点。

要完毕上述过程,须要完毕两个任务:

1、将一些数字构成堆

建堆方法:对初始序列建堆的过程,就是一个重复进行筛选的过程。

1)n 个结点的全然二叉树。则最后一个结点是第n/2个结点的子树。

2)筛选从第n/2个结点为根的子树開始,该子树成为堆。

3)之后向前依次对各结点为根的子树进行筛选。使之成为堆,直到根结点。


2、把根结点取出后,又一次构建堆

把最后一个和根结点交换。用建堆的方式(仅仅须要对第一个数进行建堆排序),再对前n-1个数进行建堆。



#include <stdio.h>

/*
1、s为第s个须要调整的数。n为整个数组的长度
   主要将每一个结点与孩子结点进行比較
*/
void headadjust(int a[],int s,int n)
{
	 int child,temp;

	    temp = a[s];
        child = 2*s+1;
        while(child < n)
		{
		     //首先找到孩子中,大的那个
			if((child+1)<n && a[child+1]>a[child])
			{
			    child++;
			}

			if(a[s]<a[child])
			{
			    a[s] = a[child];
                s = child;
				child = 2*s+1;
			}
			else
			{
			   break;
			}

			a[s] = temp;
		}


}

//每次建立堆,都将堆的根结点交换到最后,再用headadjust函数对第一个元素进行堆排序
void heap(int a[],int length)
{   
	int i,j,temp;
    for(i=(length-1)/2;i>=0;i--)
	{
	  headadjust(a,i,length);
	}
	for(j=length-1;j>=0;j--)
	{
	   temp = a[0];
	   a[0] = a[j];
	   a[j] = temp;
	   headadjust(a,0,j);
	}

}


   void main()
   {
	   int i;
	   int a[] = {3,1,5,7,2,4,9,6,10,8};  
	   int n=10;
       heap(a,n);
	   for(i = 0;i<n;i++)
	   {
	     printf("%d ",a[i]);
	   }

   
   }



原文地址:https://www.cnblogs.com/yxysuanfa/p/6776448.html