# 算法导论-1.排序算法

## 选择排序

void selectionSort(int* x, int length){
for(int i=0;i<length-1;i++){
int minValue = INT_MAX;
int minPosition = 0;
for(int j=i;j<length;j++){
if(x[j]<=minValue){
minValue=x[j];
minPosition=j;
}
}
int temp = x[minPosition];
x[minPosition]=x[i];
x[i]=temp;
}
}

## 插入排序

void insertionSort(int* x, int length){
for (int i=1;i<length;i++){
for (int j=i;j>0;j--){
if(x[j]<x[j-1]){
int temp = x[j];
x[j]=x[j-1];
x[j-1]=temp;
}
}
}
}

## 合并排序

void mergeSort(int* x, int length){
if(length==0 || length==1){
return;
}
int mid = (length-1)/2;
int child1Size = mid+1;
int* child1 = new int[child1Size];
int child2Size = length-mid-1;
int* child2 = new int[child2Size];
for(int i=0;i<mid+1;i++){
child1[i]=x[i];
}
for(int i=mid+1;i<length;i++){
child2[i-mid-1]=x[i];
}
mergeSort(child1,child1Size);
mergeSort(child2,child2Size);
{
int i=0;int j=0;int k=0;
while(k<length){
if(i==child1Size){
x[k]=child2[j];
j++;k++;continue;
}
if (j==child2Size){
x[k]=child1[i];
i++;k++;continue;
}
if(child1[i]<=child2[j]){
x[k]=child1[i];
i++;k++;continue;
}
if(child2[j]<child1[i]){
x[k]=child2[j];
j++;k++;continue;
}
}
}
return;
}

## 冒泡排序

void bubbleSort(int* x, int length)
{
for (int i=0;i<length;i++){
for (int j=length-1;j>0;j--){
if(x[j]<x[j-1]){
int temp = x[j];
x[j]=x[j-1];
x[j-1]=temp;
}
}
}
}

## 堆排序

void heapMax(int* xInput, int xSize, int i){
int l=(i+1)*2-1;
int r=(i+1)*2;
if(i>=xSize){
return;
}
if(l>=xSize && r>=xSize){
return;
}
if(xInput[i]>=xInput[l] && (r>=xSize ? true : (xInput[i]>=xInput[r]))){
return;
}
int maxI=(r>=xSize ? l : (xInput[l]>xInput[r]?l:r));
int temp = xInput[i];
xInput[i]=xInput[maxI];
xInput[maxI]=temp;
heapMax(xInput, xSize, maxI);
}
void heapMaxBuild(int* x, int length){
for(int i=length/2+1;i>=1;i--){
heapMax(x, length, i-1);
}
}
void heapSort(int* x, int length){
heapMaxBuild(x, length);
for (int i=length;i>=2;i--)    {
int temp = x[i-1];
x[i-1]=x[0];
x[0]=temp;
heapMax(x, i-1, 0);
}
}

## 快速排序

int partition(int* x, int p, int r){
int mid = x[r];
int i = p;
for (int j = p; j <= r - 1; j++){
if(x[j] <= mid){
int tmp = x[i];
x[i] = x[j];
x[j] = tmp;
i++;
}
}
int tmp = x[i];
x[i]=x[r];
x[r]=tmp;
return i;
}
void quickSort(int* x, int p, int r){
if(p < r){
int q = partition(x, p, r);
quickSort(x, p, q-1);
quickSort(x, q+1, r);
}
}
posted @ 2012-12-12 14:07  一叶斋主人  阅读(2898)  评论(4编辑  收藏  举报