排序
归并排序
#include<iostream>
#include<cassert>
using namespace std;
void Merge(int *arr, int left ,int mid , int right , int *temp)
{
int begin1 = left ;
int end1 = mid ;
int begin2 = mid + 1 ;
int end2 = right ;
int idx = left ;
while (begin1 <= end1&&begin2<=end2)
{
if (arr[begin1] < arr[begin2])
temp[idx++] = arr[begin1++];
else
temp[idx++] = arr[begin2++];
}
while (begin1<=end1)
temp[idx++] = arr[begin1++];
while (begin2<=end2)
temp[idx++] = arr[begin2++];
for (int i = left ; i<=right ; i++)
arr[i] = temp[i];
}
void _Merge_Sort(int *arr, int left , int right , int *temp)
{
if (right > left )
{
int mid = left + ((right - left ) >> 1 );
_Merge_Sort(arr, left , mid , temp);
_Merge_Sort(arr, mid + 1 , right , temp);
Merge(arr, left , mid ,right , temp);
}
}
void Merge_Sort(int *arr, int left , int right )
{
assert(right - left > 1 );
int *temp = new int [right - left + 1 ];
_Merge_Sort(arr, left , right , temp);
delete[]temp;
}
int main()
{
int arr[] = { 2 , 3 , 45 , 2 , 5 , 1 , 8 , 5 , 2 , 3 , 0 };
int len = sizeof(arr) / sizeof(arr[0 ]);
Merge_Sort(arr, 0 , len -1 );
for (int i = 0 ; i < len ; i++)
{
cout <<arr[i] << " " ;
}
cout << endl;
system("pause" );
}
插入排序
#include<iostream>
using namespace std ;
void InsertSort(int *arr, int len)
{
if (len < 2 )
return ;
for (int i = 0 ; i < len; i++)
{
int j = i - 1 ;
int key = arr[i];
while (j>-1 && arr[j]>key)
{
arr[j + 1 ] = arr[j];
--j;
}
arr[j + 1 ] = key;
}
}
int main()
{
int arr[] = { 2 , 3 , 1 , 5 , 12 , 3 , 7 , 3 , 9 , 3 , 0 , 2 };
int len = sizeof (arr) / sizeof (arr[0 ]);
InsertSort(arr, len);
for (int i = 0 ; i < len; i++)
{
cout << arr[i] << " " ;
}
cout << endl;
system("pause" );
return 0 ;
}
堆排序
#include<iostream>
using namespace std ;
class Heap_Sort
{
public :
void Sort(int *arr, int len)
{
_Build_Heap(arr, len);
while (len > 1 )
{
swap(arr[0 ], arr[len - 1 ]);
len--;
_AdjustDown(arr,0 ,len);
}
}
private :
void _Build_Heap(int *arr, int len)
{
for (int i = ((len - 2 ) >> 1 ); i >= 0 ; i--)
{
_AdjustDown(arr, i,len);
}
}
void _AdjustDown(int *arr,