1753784 Members
6945 Online
108799 Solutions
New Discussion юеВ

Awk help needed!!!

 
SOLVED
Go to solution
Ryan Clerk
Frequent Advisor

Awk help needed!!!

Hi awk expoerts,

Thank God the Forums are alive again. I've been working on this problem for two days. This should be simple. I am reading a large number of accounts into an array. Each line actually has the account number, description, total debits, and total credits separated by colons. These lines are sorted by account number so that I can search it quickly using a binary search on just the account number. My problem is that the binary search is not working. I've been over it and over it and it looks perfect. I actually copied it from an example in C that I found in the forums. My problem is that it almost never finds a matching account number.

I have simplified the array in the hope that that someone will see what's wrong. You should be able to cut and paste this and just run it as awk -f bsearch.awk. No input file is needed for this simplified example.

function bsearch(array,low,high,target,try)
{
do
{
try = (low + high) / 2;
if (target <= array[try]) high = try - 1
if (target >= array[try]) low = try + 1
}
while (high >= low)
if (low - high > 1)
{
return(try)
}
else
{
return(-1)
}
}

BEGIN {
knt = 0
while (knt < 100)
{
account_array[knt] = sprintf("%05d",10000 + knt);
++knt;
}
i = 0
while (i < 100)
{
printf("%3d %s\n",i,account_array[i]);
++i
}
i = 0
while (i < 100)
{
key = sprintf("%05d",10000 + i)
j = bsearch(account_array,0,99,key);
printf("%3d %d\n",i,j);
++i
}
}


**********************************************

Thanks for any help,
Ryan
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Awk help needed!!!

Hi Ryan:

I laughed when I saw this. There's nothing wrong with your logic just your arithmatic (or awk's).

I'll give you a big hint.

Question:
What's (2 + 5) / 2 in awk?

Answer: 3.5 not 3

You need to use the int function.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Awk help needed!!!

I'm a little curious why you are using numeric array indices. You could use awk's associative arrays (actually you are using them because that's all there is) and simply let the account number be your index.
If it ain't broke, I can fix that.
Ryan Clerk
Frequent Advisor

Re: Awk help needed!!!

Hi Clay,

Arrrgh.... I feel stupid. The int function fixed it.


Thanks,
Ryan