473,396 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to search ArrayList based on condition?

Sek
Folks,

I have an ArrayList of integers.
I have sorted the list already.

Now, i want to find the index of the first element that is greater than
a given number.

How to accomplish this in C#?

TIA.
Sek.

Nov 17 '05 #1
8 10999
Since the ArrayList already sorted, you can search for the element in
logarithmic time. http://en.wikipedia.org/wiki/Binary_search

If you have a huge number of elements, you might want to use
interpolation search.

Nov 17 '05 #2
Dear Sek,
there are a few good books on this topic like there is a
very good book by Robert Sedgewick.

Regards,
Naveed Ahmad Bajwa
http://bajoo.blogspot.com/

Nov 17 '05 #3
Sek
I have a huge number of elements. I will google for interpolation
search.

Do let me know, if u have any links to suggest.

Tks.
Sek

Nov 17 '05 #4
This might help:
http://www.dcc.uchile.cl/~rbaeza/han...22.srch.p.html
You might try comparing it to binary search for the data sets you
expect, if you aren't sure if they will be approximately evenly
distributed. You will need to make some minor changes to the algorithm
since you aren't searching for a specific key, but an interval between
two elements that contains the key.

Nov 17 '05 #5
Sek
Folks,

I will check out the same. Will get back with the results.

Tks a ton
Sek

Nov 17 '05 #6
On 16 Nov 2005 21:53:22 -0800, "Sek" <se****@gmail.com> wrote:
Folks,

I have an ArrayList of integers.
I have sorted the list already.

Now, i want to find the index of the first element that is greater than
a given number.

How to accomplish this in C#?

TIA.
Sek.


I am assuming the list is sorted from smallest to biggest integer. I
am also assuming that the following is what you want.

x == value : Return index of value
x > last value : Return index pointing beyond last value
value < x < value2 : Return index of val2

If that is the case, simply use the ArrayList BinarySearch method like
this.

static int FindIndex(System.Collections.ArrayList list, int x)
{
int index = list.BinarySearch(x);
return index < 0 ? -index - 1 : index;
}

If you wonder about -index-1, that is because the binary search method
returns a negative number when not finding a specific match. For more
information see the documentation.

--
Marcus Andrén
Nov 17 '05 #7

"Sek" <se****@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
Folks,

I have an ArrayList of integers.
I have sorted the list already.

Now, i want to find the index of the first element that is greater than
a given number.

How to accomplish this in C#?


Hi,

As other people have explained BinarySearch is a good way to go. The drawback, in your case, is that
it will find the EXACT value and not the value greater than the one that you want.

However, BinarySearch has a nice feature. If it DOESN'T find what it is looking for it will return a
negative number, which is the bitwise complement of the index of the next element. If the value
being searched for is greater than the highest value it will return the complement of the Count.

Array has similar behavior, but it is a static method in that case.
-----
So I had a thought.
Since all of your data is Integer data, you can search for a double that lies between consecutive
ints (say target + 0.1). You will NEVER get an exact match, so you will always get the next greater
value.

"Aren't I clever", I though.

But it didn't quite work out as I planned.
ArrayList(and int[] for that matter) didn't like mixing and matching boxed Int32s and Doubles.

So I played and came up with a few workarounds.

1. If you used a double[] for your collection it would work.
2. If you Forced your Ints to be stored as doubles in the ArrayList via a cast it should
work(untested)

3. Use a custom IComparer for the job...It looks like this:
public class MyComparer:IComparer
{
public int Compare(object obj1, object obj2)
{
double a = Convert.ToDouble(obj1);
double b = Convert.ToDouble(obj2);
return a.CompareTo(b);
}
}

I had to use Convert.ToDouble() rather than (double) because although this is OK
int n =2;
double d = 3.14;
int x = (int) d; // x == 3
double a = (double)n; a == 2.0

You CANNOT cast a boxed Int32 to a double or a boxed double to an Int32.

Ugh...The joy of boxing.

Sooo.....

Assuming you have an ArrayList list filled with boxed ints you can search as follows
int target = 7;
MyComparer myComparer = new MyComparer();

// negidx is the compement of the index that we want

int negidx = list.BinarySearch(target + .1, myComparer);
int idx = ~negidx;

Here is a little program (with very liitle exception saftey) to demonstrate

Good luck
Bill
---------------------------------

using System;
using System.Collections;

class Test
{
private static string prompt = "Enter target integer (ENTER to exit):";
public static void Main()
{
ArrayList list = new ArrayList();
for(int i = 0; i < 100; i++)
list.Add(i/2);

for(int i = 0; i < list.Count; i++)
Console.WriteLine("[{0,2}]:{1}",i, list[i]);
MyComparer myComparer = new MyComparer();

Console.WriteLine("------------------------");
Console.WriteLine(prompt);
string input = Console.ReadLine();
while(input != "")
{
double target = Convert.ToInt32(input) + .1;
int negidx = list.BinarySearch(target + .1, myComparer);
int idx = ~negidx;
if(idx == list.Count)
Console.WriteLine("Too Big, try a smaller number");
else
Console.WriteLine("idx:{0} negidx:{1} Value:{2}",idx,negidx, list[idx]);
Console.WriteLine(prompt);
input = Console.ReadLine();
}
Console.WriteLine("Bye");
}
}

public class MyComparer:IComparer
{
public int Compare(object obj1, object obj2)
{
double a = Convert.ToDouble(obj1);
double b = Convert.ToDouble(obj2);
return a.CompareTo(b);
}
}



Nov 17 '05 #8
Sek
Thanks Marcus and Bill for pointing to the functionality.

Bill, that was a very detailed analysis. Hats off.

I also implemented binary search on my own.
Again, i found one more issue with the BinarySearch method in C#.

Lets say, i have a million elements to search and i am looking for a
number greater than 1196. If the ArrayList has some 2000 entries of
1197.

When i search for number greater than 1196, BinarySearch returns the
index to first 1197 element. But, i actually wanted the last instance
of 1197.

Any thoughts on this?

Bill Butler wrote:
Hi,

As other people have explained BinarySearch is a good way to go. The drawback, in your case, is that
it will find the EXACT value and not the value greater than the one that you want.

However, BinarySearch has a nice feature. If it DOESN'T find what it is looking for it will


Nov 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Ben Fidge | last post by:
Hi What is the most efficient way to gather a list of files under a given folder recursively with the ability to specify exclusion file masks? For example, say I wanted to get a list of all...
5
by: Keith O | last post by:
Assume fooList is an ArrayList foreach(string s in fooList) { if (some condition) { fooList.Remove(s); } } I get the following runtime error:
1
by: ratnakarp | last post by:
Hi, I have a search text box. The user enters the value in the text box and click on enter button. In code behind on button click i'm writing the code to get the values from the database and...
10
by: JohnR | last post by:
I have an arraylist of string values. I would like to search the arraylist to find the index of a particular string and I would like the search to be case insensitive. dim al as new arraylist...
3
by: Ryan Liu | last post by:
Hi, What does ArrayList.Synchronized really do for an ArrayList? Is that equal to add lock(this) for all its public methods and properties? Not just for Add()/Insert()/Remvoe()/Count, but also...
2
by: Arsalan Ahmad | last post by:
Hi, May be I am a newbie, or may be i dont have that much insight in following systems ..i.e. why i have some confusions as below: In many websites, when search is performed on some keywords...
0
by: Seok Bee | last post by:
Dear Experts, I would like to have a listing of my current table records based on certain search criterias to list out in the gridview control. However, I have tried to use the built-in...
2
by: eSolTec, Inc. 501(c)(3) | last post by:
Thank you in advance for any and all assistance. Is there a way to start, pause and resume a recurrsive search exactly where you left off, say in the registry programmatically? -- Michael Bragg,...
2
by: grey15 | last post by:
hi...i have an application which stores records in a text file. the application loads the records in array of objects when the page is loaded. then, we can add, search, delete the records in array...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.