快速排序算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>       
using namespace std;
int BinarySearch(int a[],int x,int n);
int main()
{
int x = 6;
int a[10];
for(int i=0; i<10; i++)
{
a[i] = i + 1;
}
cout<<BinarySearch(a,x,10)<<endl;
return 0;
}

int BinarySearch(int a[],int x,int n)
{
int left = 0;
int right = n-1;
while(left<=right)
{
int mid = (left + right)/2;
if(x == a[mid])
{
return mid;
}
if(x>a[mid])
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}