What I know is Linear Search and Sequential Search are same, if my knowledge is correct then kindly guide me wether the below algorithm work for linear search or not as it is a Sequential Search algorithm.

  1. Initialize searcharray, searchno, length.
  2. Initialize pos=0.
  3. Repeat step 4 till pos<=length.
  4. if searcharray[pos]=searchno
    return pos
    else
    increment pos by 1.

Secondly I need help on how can I move found value at the first element of an array

有帮助吗?

解决方案

Linear search of a number from an array, it might be success or failed.

Your algorithm should define success or failed return. Such as position index for success and negative number for failed.

Try to think like this: Moving until you find the position.

Your number define as target. Given length and array A.

int linearSearch(int target, int* A, int length) {
  int pos = length - 1;
  while ( pos >= 0 and target != A[pos] ) --pos;
  return pos;
}

Here, If your target number is not in array, you'll get a -1 returned.

This will simple and elegant. But if you have duplicate target number, you may think how to handle them. Return one of you found or return all position.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top