// 歸併排序和快速排序演算法實現
#include
<
iostream
>
#include
#include
<
ctime
>
using
namespace
std;
//// declaration
// merge sort
template
<
class t>
void mergesort(t ar,
int num)
;template
<
class t>
void mergesort_in(t ar[
], t ta,
int low,
int high)
;template
<
class t>
void
merge
(t ar[
], t ta,
int low,
int mid,
int high)
;// quick sort
template
<
class t>
void quicksort(t ar,
int num)
;template
<
class t>
void quicksort_in(t ar,
intleft
,int
right);
template
<
class t>
intpartition
(t ar,
intleft
,int
right);
// definition
// merge sort
template
<
class t>
void mergesort(t ar,
int num)
//mergesort
template
<
class t>
void mergesort_in(t ar[
], t ta,
int low,
int high)
}//mergesort_in
template
<
class t>
void
merge
(t ar[
], t ta,
int low,
int mid,
int high)
if(i>mid)
else
// copy array back
for(k=low; k<
=high;
++k)
ar[k]
=ta[k];}
// merge
// quick sort
template
<
class t>
void quicksort(t ar,
int num)
template
<
class t>
void quicksort_in(t ar,
intleft
,int
right)}
//quicksort
template
<
class t>
intpartition
(t ar,
intleft
,int
right
)ar[
left
]=ar[j]
;ar[j]
=key;
return j;
}//partition
/// main program
int main();
int test1[9]=;
cout<<"before sort:"<
int i, j;
const
int dim1=50;
const
int dim2=100000;
int(
*arr1)
[dim2]
=new
int[dim1]
[dim2]
;int
(*arr2)
[dim2]
=new
int[dim1]
[dim2]
;// make random numbers
srand((
unsigned
)time
(null))
;// set seed
for(i=0; i++i)
}// time merge sort
clock_t start=
clock()
;for
(i=0; i++i)
quicksort(arr1[i]
, dim2)
;cout
<
<
"quick sort(50*100000): "
<
<
(double)(
clock()
-start)
/clocks_per_sec
<
<
" seconds"
<
<
endl
;// time merge sort
start=
clock()
;for
(i=0; i++i)
mergesort(arr2[i]
, dim2)
;cout
<
<
"merge sort(50*100000): "
<
<
(double)(
clock()
-start)
/clocks_per_sec
<
<
" seconds"
<
<
endl
;return 0;
}
排序演算法中 歸併排序和快速排序
氣泡排序 插入排序 選擇排序這三種演算法的時間複雜度都為分治思想,非常巧妙。1.1.歸併排序演算法實現 遞推公式 merge sort p r merge merge sort p q merge sort q 1 r 終止條件 p r 不用再繼續分解 複製 o n logn void merge ...
歸併排序和快速排序
歸併排序 先將問題分解為小問題即乙個個子序列,再將子串行按順序合併。class mergesort mergesort a,0 a.length 1 for int t a public static void mergesort int a,int m,int n public static vo...
歸併排序和快速排序
歸併排序的陣列排序任務可以如下完成 1 把前一半排序 2 把後一半排序 3 把兩半歸併到乙個新的有序陣列,然後再拷貝回原陣列,排序完成。include using namespace std void merge int a,int s,int m,int e,int tmp while p1 m ...