一个简单的数据结构举例——快排结合…

本人也是菜鸟。最近回过头来重新看数据结构。经常会把自己练习过的代码贴出来方便其他菜鸟学习,顺便保存一下写过的代码。这是VS2013下编译通过的代码。

// BSearch.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "ctime"
#define SWAP(a,b,c) (c=a,a=b,b=c)
int MAX_SIZE=1000000 ;
using namespace std;
int BSearch(int*p, int low, int high, int num);
void QuickSort(int *p,int low,int high);

int _tmain(int argc, _TCHAR* argv[])
{
int a[10000];
do
{
if (MAX_SIZE < 10000)
break;
cout << "初始化多少个数:";
} while (cin >> MAX_SIZE);
srand(unsigned (time(NULL)));
for (int i = 0; i < MAX_SIZE; i++)
a[i] = rand() % 10000;
QuickSort(a,0, MAX_SIZE-1);
for (int i = 0; i < MAX_SIZE; i++)
cout << a[i] << " ";
while (true)
{
int x;
cout <<endl<< "查找:";
cin >> x;
x=BSearch(a, 0,MAX_SIZE-1, x);

if (x)
cout << a[x-1] << "出现在第" << x << "个位置" << endl;
else
{
cout << "不存在该数" << endl;
}
}
return 0;
}


//QuickSort
void QuickSort(int *p, int low, int high)
{

if (low >= high)
{
return;
}
int i = low, j = high;
int a;
int temp = p[j];
while (i < j)
{
while (p[i] < temp)
i++;
while (p[j] >= temp && i != j)
j--;
SWAP(p[i], p[j], a);
}
SWAP(p[high], p[j], a);
QuickSort(p, low, i-1);
QuickSort(p, j + 1, high);
}




//Binary Search
int BSearch(int *p ,int low, int high,int num)
{
int m_low = low;
int m_high = high;
int mid;
while (m_low<=m_high)
{
mid = (m_low + m_high) / 2;
if (p[mid] == num)
break;

if (p[mid]>num)
m_high = mid-1;
else if (p[mid]
{
m_low = mid+1;
}
}

if (p[mid] == num)
return mid + 1;
else
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值