CSDN博客

C中的几个常用算法

#include <stdio.h>
#include <stdlib.h>

int find( int array[], int size,int date ) /*一般查找法*/
{
int i;
if( size <= 0 )
return -1;
for( i = 0; i < size; ++i )
if( date == array[i] )
return i;
return -1;
}
void swap( int *pa, int *pb )/*交换*/
{
if( (pa == NULL) || (pb == NULL) )
return ;
int temp;
temp = *pa;
*pa = *pb;
*pb = temp;
}
void m_sort( int array[],int begin, int end ) /*一般排序法*/
{
int i;
if( begin >= end )
return ;
for( i = begin + 1; i <= end; ++i )
if( array[ begin ] > array[i] )
swap( &array[ begin ], &array[i] );
m_sort( array, ++begin, end );
}
void q_sort( int array[],int begin, int end )
/*快速排序法*/
{
int i, last;

if( begin >= end )
return ;
swap( &array[ begin ], &array[ (begin + end)/2 ]);
last = begin;
for( i = begin + 1; i <= end; ++i )
if( array[i] < array[ begin ] )
swap( &array[ ++last ], &array[i] );
swap( &array[ begin ], &array[ last ] );
q_sort( array, begin, last - 1 );
q_sort( array, last + 1, end );
}
int bifind( int array[], int size, int date )
/*二分查找法*/
{
int begin, end, mid;
begin = 0;
end = size - 1;

while( begin <= end )
{
mid = (begin + end)/2;
if( date > array[ mid ] )
begin = mid + 1;
else if( date < array[ mid ] )
end = mid - 1;
else
return mid;
}
return -1;
}

0 0