归并排序
#include<iostream>
using namespace std;
void merge(int a[], int start, int middle, int end)
{
int index1 = start;
int index2 = middle + 1;
int * buffer = new int[end - start + 1];
int counter = 0;
while(index1 <= middle && index2 <= end)
{
if(a[index1] <= a[index2])
buffer[counter++] = a[index1++];
else
buffer[counter++] = a[index2++];
}
if(index1 <= middle)
{
while(index1 <= middle)
buffer[counter++] = a[index1++];
}
else
{
while(index2 <= end)
buffer[counter++] = a[index2++];
}
for(int i = 0; i < counter; i++)
a[start + i] = buffer[i];
}
void mergeSort(int a[], int start, int end)
{
if(start == end)
return;
int middle = (start + end) / 2;
mergeSort(a, start, middle);
mergeSort(a, middle + 1, end);
merge(a, start, middle, end);
return;
}
int main()
{
int a[] = {9, 10, 23, 14, 12};
mergeSort(a, 0, sizeof(a) / sizeof(int) - 1);
for(int i = 0; i < sizeof(a) / sizeof(int); i++)
cout << a[i] << " ";
getchar();
}
快速排序
#include<iostream>
using namespace std;
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int partition(int a[], int start, int end)
{
int pivot = a[start];
int left = start;
int right = end;
while(left < right)
{
while(left <= end && a[left] <= pivot) left++;
while(right >= start && a[right] > pivot) right--;
if(left < right) swap(&a[left], &a[right]);
}
int middle = right;
swap(&a[start], &a[middle]);
return right;
}
void quickSort(int a[], int start, int end)
{
if(start == end)
return;
int index = partition(a, start, end);
if(index > start)
quickSort(a, start, index - 1);
if(index < end)
quickSort(a, index + 1, end);
return;
}
int main()
{
int a[] = {9, 10, 23, 14, 12};
quickSort(a, 0, sizeof(a) / sizeof(int) - 1);
for(int i = 0; i < sizeof(a) / sizeof(int); i++)
cout << a[i] << " ";
getchar();
}
二分查找
#include<iostream>
using namespace std;
int binarySearch(int a[], int start, int end, int target)
{
while(start <= end)
{
int middle = (start + end) / 2;
if(a[middle] == target)
return middle;
if(a[middle] > target)
end = middle - 1;
else
start = middle + 1;
}
return 2147483647;//用2147483647表示没有找到
}
int main()
{
int a[] = {9, 10, 23, 24, 32};
int i = binarySearch(a, 0, sizeof(a) / sizeof(int) - 1, 32);
cout << i << " ";
getchar();
}