#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
#include<algorithm>
//快速查找
int Find(int m[], int right, int elem)
{
int left = 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (m[mid - 1] == elem)
return mid;
if (m[mid - 1] < elem)
left = mid + 1;
else
right = mid - 1;
}
return 0;
}
bool comp(int a, int b)
{
return a < b;
}
int _tmain(int argc, _TCHAR* argv[])
{
char st[200] = {0};
int m_num[100];
gets(st);
//把输入的字符串分离(例子: st = "123 432 4 5 4 5 65 4 456");
char *p = strtok(st, " ");
int n = 0;
while (p != NULL)
{
m_num[n++] = atoi(p);
p = strtok(NULL, " ");
}
std::sort(m_num, m_num + n, comp); //排序
while (1)
{
printf("请输入查找元素:");
int m = 0;
scanf("%d", &m);
if (!m)
break;
int index = Find(m_num, n, m);
if (!index)
{
printf("没有你要查找的元素\n");
continue;
}
printf("索引:%d\n", index);
}
system("pause");
return 0;
}
#include <stdlib.h>
#include <iostream>
#include <string>
#include<algorithm>
//快速查找
int Find(int m[], int right, int elem)
{
int left = 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (m[mid - 1] == elem)
return mid;
if (m[mid - 1] < elem)
left = mid + 1;
else
right = mid - 1;
}
return 0;
}
bool comp(int a, int b)
{
return a < b;
}
int _tmain(int argc, _TCHAR* argv[])
{
char st[200] = {0};
int m_num[100];
gets(st);
//把输入的字符串分离(例子: st = "123 432 4 5 4 5 65 4 456");
char *p = strtok(st, " ");
int n = 0;
while (p != NULL)
{
m_num[n++] = atoi(p);
p = strtok(NULL, " ");
}
std::sort(m_num, m_num + n, comp); //排序
while (1)
{
printf("请输入查找元素:");
int m = 0;
scanf("%d", &m);
if (!m)
break;
int index = Find(m_num, n, m);
if (!index)
{
printf("没有你要查找的元素\n");
continue;
}
printf("索引:%d\n", index);
}
system("pause");
return 0;
}