---
title: "一些常用的排序和查找算法（折半冒泡快排选择归并）"
author: "lee_3do"
date: "2010-10-06T21:38:53Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-10-10T11:23:20Z"
id: 777888
url: "https://lee3do.iteye.com/blog/777888"
---

折半查找：

 

```
//折半查找
int BinarySearch(int num,int a[],int length)
{
	int left=0;
	int right=length-1;
    while(left<right)
	{
		int middle=(left+right)/2;
		if(a[middle]==num)
			return middle;
		else if(a[middle]>num)
			right=middle-1;
		else
			left=middle+1;
	}
	return -1;
}
```

 冒泡排序：

 

```
//冒泡排序
int BubbleSort(int a[],int length)
{
	for(int i=0;i<length;i++)
		for(int j=0;j<(length-i);j++)
		{
			if(a[j]>a[j+1])
				swap(a[j],a[i+1]);
		}
}
```

 快速排序（有点小问题，忘了跳出迭代了）：

 

```
//快速排序
void QuickSort(int a[],int left,int right)
{
    int pivotpos=Partition(a,left,right);
    QuickSort(a,left,pivotpos-1);
    QuickSort(a,pivotpos+1,right);
}

//把小于基准的搞到左边，大于基准的去右边
int Partition(int a[],int low,int high)
{
    int pivot = a[low];
    int pos=low;
    for(int i=low+1;i<high;i++)
    {
        if(a[i]<pivot)
        {
            Swap(a[i],a[pos]);
            pos++;
         }
    }
    return pos;
}
```

```
//选择排序，算法思想：每一次从后面n-i个待排序对象中选择一个最小的，
//放在第n个位置，话说这算法时间复杂度真的很高...

void SelectSort(int a[],int length)
{
    for(int i=0;i<length;i++)
        Exchange(a,i,length);
}
//从后面n-i个待排序对象中选择一个最小的，放在第n个位置
void Exchange(int a[],int i,int length)
{
    int min = a[i];
    int index=i;
    for(int m=i+1;i<length;i++)
    {
        if(a[m]<min)
        {
            min=a[m];
            index=m;
        }
    }
    swap(a[i],a[index]);
}
```

```
//归并排序，两个已经排好顺序的数组，合并成一个数组
int* Merge(int a[],int b[],int aLength,int bLength)
{
    int cLength = aLength+bLength;
    int* c=new int[cLength];
    int aIndex=0,bIndex=0,cIndex=0;
    while(aIndex<aLength&&bIndex<bLength)
        c[cIndex++]=a[aIndex]<b[bIndex]?a[aIndex++]:b[bIndex++];
    while(aIndex<aLength)
        c[cIndex++]=a[aIndex++];
     while(bIndex<bLength)
        c[cIndex++]=b[bIndex++];
        return c;
}
```

```
shell排序：先比较距离远的元素，这样可以快速减少大量的无需情况，从而减轻后续工作。
```