算法学习
排序综合
直接插入排序
void insert_sort ( int arr[ ] , int length)
{
int i, j;
for ( i = 1 ; i < length; i++ )
{
int tem = arr[ i] ;
for ( j = i; j > 0 && arr[ j - 1 ] > tem; j-- )
arr[ j] = arr[ j - 1 ] ;
arr[ j] = tem;
}
}
希尔排序(插入排序改进)
void shell_sort ( int arr[ ] , int length)
{
int i, j, k;
for ( k = length / 2 ; k > 0 ; k / = 2 )
{
for ( i = k; i < length; i++ )
{
int tem = arr[ i] ;
for ( j = i; j > 0 && arr[ j - k] > tem; j - = k)
arr[ j] = arr[ j - k] ;
arr[ j] = tem;
}
}
}
冒泡排序
void bubble_sort ( int arr[ ] , int length)
{
int i, j;
for ( i = 0 ; i < length - 1 ; i++ )
{
for ( j = 0 ; j < length - 1 - i; j++ )
{
if ( arr[ j] > arr[ j + 1 ] )
{
int tem = arr[ j + 1 ] ;
arr[ j + 1 ] = arr[ j] ;
arr[ j] = tem;
}
}
}
}
快速排序(冒泡排序升级)
void quick_sort ( int arr[ ] , int left, int right)
{
if ( left >= right)
return ;
int i, j, k;
i = left;
j = right;
k = arr[ left] ;
while ( i < j)
{
while ( i < j && arr[ j] >= k)
j-- ;
arr[ i] = arr[ j] ;
while ( i < j && arr[ i] <= k)
i++ ;
arr[ j] = arr[ i] ;
}
arr[ i] = k;
quick_sort ( arr, left, i - 1 ) ;
quick_sort ( arr, i+ 1 , right) ;
}
归并排序
void mergearray ( int arr[ ] , int left, int mid, int right, int temp[ ] )
{
int i, j, k;
i = left;
j = mid+ 1 ;
k = 0 ;
while ( i <= mid && j <= right)
if ( arr[ i] < arr[ j] )
temp[ k++ ] = arr[ i++ ] ;
else
temp[ k++ ] = arr[ j++ ] ;
while ( i <= mid)
{
temp[ k++ ] = arr[ i++ ] ;
}
while ( j <= right)
{
temp[ k++ ] = arr[ j++ ] ;
}
for ( int i = 0 ; i < k; i++ )
arr[ left+ i] = temp[ i] ;
}
void mergesort ( int arr[ ] , int left, int right, int temp[ ] )
{
if ( left < right)
{
int mid = ( left + right) / 2 ;
mergesort ( arr, left, mid, temp) ;
mergesort ( arr, mid + 1 , right, temp) ;
mergearray ( arr, left, mid, right, temp) ;
}
}
bool merge_sort ( int arr[ ] , int n)
{
int * p = ( int * ) malloc ( n * sizeof ( int ) ) ;
if ( ! p)
return false;
mergesort ( arr, 0 , n - 1 , p) ;
free ( p) ;
return true;
}
//adrai.github.io/flowchart.js/