c语言 快速排序---归并排序----堆排序

//快速排序:

#include <stdio.h>
#define MAX 500000
int s[MAX];
void Q_Sort(int start,int end)
{
int i,j,t;
if ( start >= end ) return ;
t = s[start];
i = start;
j = end;
while ( i < j)
{
while ( s[j] >= t && i < j)
{
j--;
}
s[i] = s[j];
while ( s[i] <= t && i < j)
{
i++;
}
s[j] = s[i];
}
s[i] = t;
Q_Sort(start,i-1);
Q_Sort(i+1,end);
}
int main()
{
int i,n;
while (scanf("%d",&n),n)
{
for ( i = 0 ; i < n ; i++)
{
scanf("%d",&s[i]);
}
Q_Sort(0,n-1);
}
return 0;
}

  


//归并排序

#include <stdio.h>
#define MAX 500000
int a[MAX];
int b[MAX];
void Merge(int left,int mid,int right)
{
int i,j,k;
i = left;
j = mid+1;
k = left;
while ( i <= mid && j <= right )
{
if ( a[i] <= a[j] )
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
}
}
while ( i <= mid )
{
b[k++] = a[i++];
}
while ( j <= right )
{
b[k++] = a[j++];
}
}
void MergeSort(int left,int right)
{
int i,mid;
if ( left < right )
{
mid = ( left + right ) / 2 ;
MergeSort(left , mid);
MergeSort(mid+1 , right);
Merge(left,mid,right);
for ( i = left ; i <= right ; i++)
{
a[i] = b[i];
}
}
}
int main()
{
int i,n;
while (scanf("%d",&n),n)
{
for ( i = 0 ; i < n ; i++)
{
scanf("%d",&a[i]);
}
MergeSort(0,n-1);
}
return 0;
}         

  


//堆排:

#include <stdio.h>
#define MAX 500000
int s[MAX];
void Heapify(int x,int n)
{
if ( x*2+1 <= n)
{
if ( s[x] == s[2*x] && s[x] == s[2*x+1] ) return ;
if ( s[2*x] > s[x] && s[2*x] > s[2*x+1] )
{
s[2*x] ^= s[x] ^= s[2*x] ^= s[x] ;
Heapify(2*x,n);
}
else if ( s[2*x+1] > s[x] && s[2*x+1] > s[2*x] )
{
s[2*x+1] ^= s[x] ^= s[2*x+1] ^= s[x] ;
Heapify(2*x+1,n);
}
else if ( s[2*x+1] == s[2*x] && s[2*x] > s[x])
{
s[2*x] ^= s[x] ^= s[2*x] ^= s[x];
Heapify(2*x,n);
}
}
else if ( x*2 == n )
{
if ( s[2*x] > s[x] )
{
s[2*x] ^= s[x] ^= s[2*x] ^= s[x] ;
Heapify(2*x,n);
}
}
}
void HeapSort(int n)
{
int i,k;
for ( i = n/2 ; i >= 1 ; i--)
{
Heapify(i,n);
}
for ( k = n ; k > 1 ; k--)
{
s[k] ^= s[1] ^= s[k] ^= s[1];
Heapify(1,k-1);
}
}
int main()
{
int i,n;
while (scanf("%d",&n),n)
{
for ( i = 1 ; i <= n ; i++)
{
scanf("%d",&s[i]);
}
HeapSort(n);
for ( i = 1 ; i <= n ; i++)
{
if ( i != n ) printf("%d ",s[i]);
else printf("%d\n",s[i]);
}
}
return 0;
}

  


 
 
上一篇:rac中 kull session会话脚本


下一篇:JS模拟CSS3动画-贝塞尔曲线