您的位置:首页 > 其它

快排,二分查找

2016-05-30 10:03 253 查看
// search_Bin.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

int binSearch(int a[6], int x, int len );

int posFun(int * a, int low, int heigh);

int binSearch(int a[6], int x, int len ){

int low = 0;
int heigh = len - 1;
int mid;

while (low <= heigh)
{
mid = (low + heigh)/2;
if (a[mid] < x)
{
low = mid + 1;
}else{
if(a[mid] > x){
heigh = mid - 1;
}else{
return mid;
}
}
}

return -100;

}

void quickSort(int a[], int low, int heigh){

int positacion = 0;
positacion = posFun(a, low, heigh);

if (low < heigh)
{
quickSort(a, low, positacion -1);
quickSort(a, positacion + 1, heigh);
}
}

int posFun(int * a, int low, int heigh){

int var = a[low];

//while循环退出的条件是 low == heigh 这点要注意
while (low < heigh)
{

while (low < heigh && (a[heigh] > var ))
--heigh;
a[low] = a[heigh];

while (low < heigh && a[low] < var)
++low;
a[heigh] = a[low];

}

a[low] = var;

return low;

}

int _tmain(int argc, _TCHAR* argv[])
{
int a[6] = {1, 2, 3, 4, 5, 6};

int resultVal;

resultVal = binSearch(a, 4, 6);

printf("the val is %d", resultVal);

int b[6] = {3, 1, 4, 8, 9};

quickSort(b, 0, 5);

for (int i = 0; i < 5; i++)
{
printf("the val is %d", b[i]);
}

return 0;
}

void BubbleSort(int x[],int n)
{
int i,j;
bool Exchange;  //记录交换标志
for(int i=1;i < n - 1; i++)    //最多做n-1趟排序
{
Exchange = false;
for(j=n-1;j>=i;--j)
{
if(x[j]>x[j+1])
{
x[0] = x[j];
x[j] = x[j+1];
x[j+1] = x[0];
Exchange = true;   //发生了交换,设置标志为真.
}
}
if (!Exchange )      //为发生替换,提前终止算法
return;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: