searching+sorting

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<iostream.h>

typedef enum boolean{false=0,true=1};
boolean found;
void sorting(int array[]);
int data[10]={1,4,36,5,6,3,7,8,32,35};
search(int a);
int s;
main()
{
	int i;
	sorting(data);
		for(i=0;i<10;i++)
		{
			cout<<data[i]<<" ";
		}
		cout<<"\n Find data: ";
			cin>>s;
			search(s);

		return 0;
}


void sorting(int array[])
{
	int i,j,temp;
	found=false;

	for(i=0;i<10;i++)
	{
		for(j=0;j<9;j++)
		{
			if(data[i]<data[j])
		  {
				temp=data[i];
				data[i]=data[j];
				data[j]=temp;
		  }
		}
	}
}


search(int a)
{
	int k,first=0,last=10;

	while((!found)&(first<=last))
	{
		 k=(first+last)/2;
			if(s==data[k])
			{
				found=true;
			}
		else
			if(s<data[k])
			{
				first=k-1;
			}
			else
				last=k+1;
	}

	if(found)
	{
		cout<<s<<" was found in index-"<<k;
	}
	else
	cout<<"not found";
}


I dont know..when I put the number program will not responding?
can help me??
1) you need to get a better c++ textbook. Your's teaches you ANCIENT style. Or maybe you are coming from a C background?

2) If it hangs, check your loops. They most probably have wrong conditions when they should stop.
E.g. while((!found)&(first<=last)) looks suspicious. Maybe you mean && ?


Ciao, Imi.
"&&" not work imi
yeah I'm from C backgroud....
If you just need to get the job done, use the STL instead of writing your own search. sort() and lower_bound() is probably what you want here.

If you have to do it by yourself (homework, exercise, etc..)

I recommend you search for an example of binary search in C++. I bet wikipedia has one. Getting this done correctly is hard! There can be a lot of subtle small problems everywhere.

(Or you could try to decipher your std::lower_bound, but the STL-stuff source code is usually very hard to read).

If you really want to sit this through by yourself, best is to use a debugger and step-by-step execute your loop until you find out why it does not quit correctly.

If you even don't want / can't use a graphical debugger, then it's paper-time. Grab a piece of paper and go through the code by hand and write down what state each variable has step by step. But I think that's ridiculous. ;-). As an alternative, you can write "cout << " statements all over the place to get some debug-output.

Ciao, Imi.
the easiest way would be to do a linear search, though not efficient.
http://www.functionx.com/cpp/examples/linearsearch.htm

anyway in your sort() function, passing the array is useless for data is already global..
Topic archived. No new replies allowed.