1
//此段代码可以让数组传递长度
2
//调用方法int a[]={1,2,3,4,5};
3
//f(a);
4
//template<typename Type , int Size> void
5
//f(Type (&arr)[Size])
6
//{
7
// cout<<Size<<sizeof(arr)<<endl;
8
//}
9
10
//template <class elemType> elemType min(elemType a,elemType b)
11
//{
12
// return a < b ? a : b;
13
//}
//此段代码可以让数组传递长度2
//调用方法int a[]={1,2,3,4,5};3
//f(a);4
//template<typename Type , int Size> void5
//f(Type (&arr)[Size])6
//{7
// cout<<Size<<sizeof(arr)<<endl;8
//}9

10
//template <class elemType> elemType min(elemType a,elemType b)11
//{12
// return a < b ? a : b;13
//}
快速排序
1
template <class elemType> void swap(elemType arr[],int i,int j)
2
{
3
elemType tem=arr[i];
4
arr[i]=arr[j];
5
arr[j] = tem;
6
}
7
8
template <class elemType> void display(elemType arr[] ,int size)
9
{
10
for(int i=0;i<size;i++)
11
cout<<arr[i]<<" ";
12
cout<<endl;
13
}
14
15
template <class elemType> void sort(elemType arr[],int low ,int high )
16
{
17
18
if ( low < high )
19
{
20
int lo = low;
21
int hi = high + 1;
22
elemType elem = arr[lo];
23
24
for (;;)
25
{
26
while ( min( arr[++lo], elem ) != elem && lo < high ) ;
27
while ( min( arr[--hi], elem ) == elem && hi > low ) ;
28
if (lo < hi)
29
swap( arr, lo, hi );
30
else break;
31
}
32
swap( arr, low, hi );
33
sort( arr, low, hi-1 );
34
sort( arr, hi+1, high );
35
}
36
}
37
38
int _tmain(int argc, _TCHAR* argv[])
39
{
40
int a [] = {1,3,2,4,6,5,7};
41
//int b[] = {2,1};
42
//sort(b,0,1);
43
sort(a,0,6);
44
display(a,sizeof(a)/sizeof(int));
45
return 0;
46
}
template <class elemType> void swap(elemType arr[],int i,int j)2
{3
elemType tem=arr[i];4
arr[i]=arr[j];5
arr[j] = tem;6
}7

8
template <class elemType> void display(elemType arr[] ,int size)9
{10
for(int i=0;i<size;i++)11
cout<<arr[i]<<" ";12
cout<<endl;13
}14

15
template <class elemType> void sort(elemType arr[],int low ,int high )16
{17

18
if ( low < high ) 19
{ 20
int lo = low; 21
int hi = high + 1; 22
elemType elem = arr[lo]; 23
24
for (;;) 25
{ 26
while ( min( arr[++lo], elem ) != elem && lo < high ) ; 27
while ( min( arr[--hi], elem ) == elem && hi > low ) ; 28
if (lo < hi) 29
swap( arr, lo, hi ); 30
else break; 31
} 32
swap( arr, low, hi ); 33
sort( arr, low, hi-1 ); 34
sort( arr, hi+1, high ); 35
}36
}37

38
int _tmain(int argc, _TCHAR* argv[])39
{40
int a [] = {1,3,2,4,6,5,7};41
//int b[] = {2,1}; 42
//sort(b,0,1);43
sort(a,0,6);44
display(a,sizeof(a)/sizeof(int));45
return 0;46
}

