Merge Sort——from bottom to top(iteration)
void merge_sort ( ElementType list[ ] , ElementType sorted[ ] , int N, int length ) { int size= 1 ; for ( ; size< N; size*= 2 ) { for ( int i= 0 ; i< N; i+= 2 * size) { int l1= i; int l2= size+ i; int loc= l1; while ( l1< i+ size&& l1< N&& l2< i+ 2 * size&& l2< N) { if ( list[ l1] < list[ l2] ) sorted[ loc++ ] = list[ l1++ ] ; else sorted[ loc++ ] = list[ l2++ ] ; } while ( l1< i+ size&& l1< N) sorted[ loc++ ] = list[ l1++ ] ; while ( l2< i+ 2 * size&& l2< N) sorted[ loc++ ] = list[ l2++ ] ; } for ( int i= 0 ; i< N; i++ ) { printf ( "%d " , sorted[ i] ) ; list[ i] = sorted[ i] ; } printf ( "\n" ) ; } return ;
}
from top to bottom(recursion)
将两个有序表合并为一个有序表,空间O(N),时间O(N)
在时间复杂度=O(N)的前提下,最优的空间复杂度可以是O(1)吗
void Merge ( ElemType A[ ] , int low, int mid, int high) { for ( int k= low; k<= high; k++ ) B[ k] = A[ k] ; for ( int i= low, j= mid+ 1 , k= i; i<= mid&& j<= high; k++ ) { if ( B[ i] <= B[ j] ) A[ k] = B[ i++ ] ; else A[ k] = B[ j++ ] ; } while ( i<= mid) A[ k++ ] = A[ i++ ] ; while ( j<= high) A[ k++ ] = A[ j++ ] ;
}
利用1)分解为子归并
void MergeSort ( ElemType A[ ] , int low, int high) { if ( low<= high) { int mid= ( low+ high) / 2 ; MergeSort ( A, low, mid) ; MergeSort ( A, mid+ 1 , high) ; Merge ( A, low, mid, high) ; }
}
Heap Sort
过程
堆排序=1) 构造大顶堆,若是比左右小,要下移到底部 +heap_pass=2)交换顶元素;3)顶元素下降 1,2公用一个move_down(),边界条件 用 sign+(loc,val)
void move_down ( vector< int > & array, int heap_size, int tra) { int sign= 1 ; while ( sign) { int loc= tra, val= array[ tra] ; int renew= 0 ; if ( ( 2 * tra+ 1 < heap_size) && array[ 2 * tra+ 1 ] > array[ tra] ) { loc= 2 * tra+ 1 ; val= array[ 2 * tra+ 1 ] ; renew= 1 ; } if ( ( 2 * tra+ 2 < heap_size) && array[ 2 * tra+ 2 ] > val) { loc= 2 * tra+ 2 ; val= array[ 2 * tra+ 2 ] ; renew= 1 ; } if ( renew== 1 ) { swap ( array[ tra] , array[ loc] ) ; tra= loc; } else break ; }
}
void build_heap ( vector< int > & array, int heap_size) { for ( int i= heap_size/ 2 - 1 ; i> - 1 ; i-- ) { move_down ( array, heap_size, i) ; }
}
void heap_pass ( vector< int > & array, int heap_size) { swap ( array[ 0 ] , array[ heap_size- 1 ] ) ; move_down ( array, heap_size- 1 , 0 ) ; return ;
}
划水
一个晚上就写了3个排序,菜烂了www,但总比没有强,打个卡