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.

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

Secondly I need help on how can I move the found value at the first element of an array, I have this code which can find value which user enter in an array using linear search.

``````#include <iostream.h>
#include<conio.h>
int linearSearch(const int a[], int size, int key);
int main() {
const int SIZE = 8;
int a1[SIZE] = {8, 4, 5, 3, 2, 9, 4, 1};

cout << linearSearch(a1, SIZE, 8) << endl;  // 0
cout << linearSearch(a1, SIZE, 4) << endl;  // 1
}

// Search the array for the given key
// If found, return array index [0, size-1]; otherwise, return size
int linearSearch(const int a[], int size, int key) {
for (int i = 0; i < size; ++i) {
if (a[i] == key) return i;
}
return size;
}
``````
2
Contributors
1
13
Views
5 Years
Discussion Span
Last Post by deceptikon

Step 2. Initialize pos=0.
Step 3. Repeat step 4 till pos<=length.

When starting at 0, that implies a half open range. Step 3 is wrong in that it says to repeat until pos is less than or equal to `length`. In other words, the loop will never run because `pos` will never be less than `length`.

Instead, step 3 should read "Repeat step 4 until pos = length". This stops the loop when `pos` is equal to `length` so that the array isn't indexed out of bounds.

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

So you want to move the located value to the first element? What happens to the other elements? Typically there are two approaches to a move-first algorithm:

1. Swap the current first with the found value.

``````for (i = 0; i < n; i++) {
if (is_match(a[i])) {
break;
}
}

if (i != 0) {
swap(a[0], a[i]);
}
``````
2. Shift all values to fill in the vacated hole, then copy the value to the first position.

``````for (i = 0; i < n; i++) {
if (is_match(a[i])) {
break;
}
}

if (i != 0) {
save = a[i];

while (i > 0) {
a[i] = a[i - 1];
--i;
}

a[0] = save;
}
``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.