0

How to do linear I want to get the position for an item in the array to insert , I mean the index where I have to insert the data in the array. How can I achieve this by using Linear search only . Suggestions Please.

2 Answers 2

0

Linear search for example with a for loop:

int[] test = new int[1024]; 
// i assume you have something like this

int searchnumber = 17;

int foundindex = -1;

for(int i = 0; i < count, i++)
{
if (test[i] == 17)
{
    foundindex = i;
    break;
}
}

// now you have the found index in foundindex

If your array is sorted you could use a binary search, but since you asked for a linear search tghis should do the trick.

6
  • No the array wont be in sorted, but see I have an array of (4, 6 , 8 ,10 ) i want the position for the element 9 which I want to insert into the array.. Apr 2, 2012 at 12:51
  • But your example array is sorted, or do i get something wrong?
    – S.Spieker
    Apr 2, 2012 at 12:55
  • think tat array is sorted initally , I have an array of ( 4 , 0 , 8 ,5 , 3) for each item how can I get the best positions ? Apr 2, 2012 at 12:58
  • i would sort the array in the beginning and then use a binary search. So you only have one time a little overhead and are really fast when searching items.
    – S.Spieker
    Apr 2, 2012 at 13:03
  • addign items to array will be random, so while adding to the array I need the best position Apr 2, 2012 at 13:05
0

Find the nearest possible value and insert before or after it depending on your need

    loop
    {
    int index = [arrResultRow indexOfObject:10];
    [arrResultRow insertObject:object atIndex:index+1]
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.