Improving Linear Search Technique

13 Jan, 2022
A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. It is observed that when searching for a key element, then there is a possibility for searching the same key element again and again.
The goal is that if the same element is searched again then the operation must take lesser time. Therefore, in such a case, Linear Search can be improved by using the following two methods: 
TranspositionMove to Front
Transposition
Move to Front
In transposition, if the key element is found, it is swapped to the element an index before to increase in a number of search count for a particular key, the search operation also optimizes and keep moving the element to the starting of the array where the searching time complexity would be of constant time. 
For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: 
After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 1, 4, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 4.
Again after searching for key 4, the element is found at index 4 of the given array after 6 comparisons. Now after transposition, the array becomes {2, 5, 7, 4, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 3.
The above process will continue until any key reaches the front of the array if the element to be found is not at the first index.
Below is the implementation of the above algorithm discussed:
C++
C
Java
C#
Python3
// C++ program for transposition to// improve the Linear Search Algorithm#include <iostream>using namespace std; // Structure of the arraystruct Array {     int A[10];    int size;    int length;}; // Function to print the array elementvoid Display(struct Array arr){    int i;     // Traverse the array arr[]    for (i = 0; i < arr.length; i++) {        cout <<" "<< arr.A[i];    }    cout <<"\n";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){    // Store the value store at    // x in a variable temp    int temp = *x;     // Swapping of value    *x = *y;    *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition(    struct Array* arr, int key){    int i;     // Traverse the array    for (i = 0; i < arr->length; i++) {         // If key is found, then swap        // the element with it's        // previous index        if (key == arr->A[i]) {             // If key is first element            if (i == 0)                return i;             swap(&arr->A[i],                 &arr->A[i - 1]);             return i;        }    }    return -1;} // Driver Codeint main(){    // Given array arr[]    struct Array arr        = { { 2, 23, 14, 5, 6, 9, 8, 12 },            10,            8 };     cout <<"Elements before Linear"           " Search Transposition: ";     // Function Call for displaying    // the array arr[]    Display(arr);     // Function Call for transposition    LinearSearchTransposition(&arr, 14);     cout <<"Elements after Linear"           " Search Transposition: ";     // Function Call for displaying    // the array arr[]    Display(arr);    return 0;} // this code is contributed by shivanisinghss2110
// C program for transposition to// improve the Linear Search Algorithm#include <stdio.h> // Structure of the arraystruct Array {     int A[10];    int size;    int length;}; // Function to print the array elementvoid Display(struct Array arr){    int i;     // Traverse the array arr[]    for (i = 0; i < arr.length; i++) {        printf("%d ", arr.A[i]);    }    printf("\n");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){    // Store the value store at    // x in a variable temp    int temp = *x;     // Swapping of value    *x = *y;    *y = temp;} // Function that performs the Linear// Search Transpositionint LinearSearchTransposition(    struct Array* arr, int key){    int i;     // Traverse the array    for (i = 0; i < arr->length; i++) {         // If key is found, then swap        // the element with it's        // previous index        if (key == arr->A[i]) {             // If key is first element            if (i == 0)                return i;             swap(&arr->A[i],                 &arr->A[i - 1]);             return i;        }    }    return -1;} // Driver Codeint main(){    // Given array arr[]    struct Array arr        = { { 2, 23, 14, 5, 6, 9, 8, 12 },            10,            8 };     printf("Elements before Linear"           " Search Transposition: ");     // Function Call for displaying    // the array arr[]    Display(arr);     // Function Call for transposition    LinearSearchTransposition(&arr, 14);     printf("Elements after Linear"           " Search Transposition: ");     // Function Call for displaying    // the array arr[]    Display(arr);    return 0;}
// Java program for transposition// to improve the Linear Search// Algorithmclass GFG{ // Structure of the// arraystatic class Array{  int []A = new int[10];  int size;  int length;  Array(int []A, int size,        int length)  {    this.A = A;    this.size = size;    this.length = length;  }}; // Function to print the// array elementstatic void Display(Array arr){  int i;   // Traverse the array arr[]  for (i = 0; i < arr.length; i++)  {    System.out.printf("%d ",                      arr.A[i]);  }  System.out.printf("\n");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr,                                     int key){  int i;   // Traverse the array  for (i = 0; i < arr.length; i++)  {    // If key is found, then swap    // the element with it's    // previous index    if (key == arr.A[i])    {      // If key is first element      if (i == 0)        return i;      int temp = arr.A[i];      arr.A[i] = arr.A[i - 1];      arr.A[i - 1] = temp;      return i;    }  }  return -1;} // Driver Codepublic static void main(String[] args){  // Given array arr[]  int tempArr[] = {2, 23, 14, 5,                   6, 9, 8, 12};  Array arr = new Array(tempArr,                        10, 8);   System.out.printf("Elements before Linear" +                    " Search Transposition: ");   // Function Call for displaying  // the array arr[]  Display(arr);   // Function Call for transposition  LinearSearchTransposition(arr, 14);   System.out.printf("Elements after Linear" +                    " Search Transposition: ");   // Function Call for displaying  // the array arr[]  Display(arr);}} // This code is contributed by Princi Singh
// C# program for transposition// to improve the Linear Search// Algorithmusing System; class GFG{ // Structure of the// arraypublic class Array{    public int []A = new int[10];    public int size;    public int length;         public Array(int []A, int size,                 int length)    {        this.A = A;        this.size = size;        this.length = length;    }}; // Function to print the// array elementstatic void Display(Array arr){    int i;         // Traverse the array []arr    for(i = 0; i < arr.length; i++)    {        Console.Write(arr.A[i] + " ");    }    Console.Write("\n");} // Function that performs the Linear// Search Transpositionstatic int LinearSearchTransposition(Array arr,                                     int key){    int i;         // Traverse the array    for(i = 0; i < arr.length; i++)    {                 // If key is found, then swap        // the element with it's        // previous index        if (key == arr.A[i])        {                         // If key is first element            if (i == 0)                return i;                             int temp = arr.A[i];            arr.A[i] = arr.A[i - 1];            arr.A[i - 1] = temp;            return i;        }    }    return -1;} // Driver Codepublic static void Main(String[] args){         // Given array []arr    int []tempArr = { 2, 23, 14, 5,                      6, 9, 8, 12 };    Array arr = new Array(tempArr, 10, 8);         Console.Write("Elements before Linear " +                  "Search Transposition: ");         // Function Call for displaying    // the array []arr    Display(arr);         // Function Call for transposition    LinearSearchTransposition(arr, 14);         Console.Write("Elements after Linear " +                  "Search Transposition: ");         // Function Call for displaying    // the array []arr    Display(arr);}} // This code is contributed by Amit Katiyar
# Python3 program for transposition to# improve the Linear Search Algorithm  # Structure of the arrayclass Array :    def __init__(self,a=[0]*10,size=10,l=0) -> None:        self.A=a        self.size=size        self.length=l # Function to print array elementdef Display(arr):     # Traverse the array arr[]    for i in range(arr.length) :        print(arr.A[i],end=" ")         print()  # Function that performs the Linear# Search Transpositiondef LinearSearchTransposition(arr, key):     # Traverse the array    for i in range(arr.length) :         # If key is found, then swap        # the element with it's        # previous index        if (key == arr.A[i]) :             # If key is first element            if (i == 0):                return i             arr.A[i],arr.A[i - 1]=arr.A[i - 1],arr.A[i]             return i                  return -1  # Driver Codeif __name__ == '__main__':    # Given array arr[]    arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8)     print("Elements before Linear Search Transposition: ")     # Function Call for displaying    # the array arr[]    Display(arr)     # Function Call for transposition    LinearSearchTransposition(arr, 14)     print("Elements after Linear Search Transposition: ")     # Function Call for displaying    # the array arr[]    Display(arr)
In this method, if the key element is found then it is directly swapped with the index 0, so that the next consecutive time, search operation for the same key element is of O(1), i.e., constant time. 
For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: 
After searching for key 4, the element is found at index 5 of the given array after 6 comparisons. Now after moving to front operation, the array becomes {4, 2, 5, 7, 1, 6, 5, 8, 3, 7} i.e., the key with value 4 comes at index 0.
Again after searching for key 4, the element is found at index 0 of the given array which reduces the entire’s search space.
C++
C
Java
C#
Python3
// C program to implement the move to// front to optimized Linear Search#include <iostream>using namespace std; // Structure of the arraystruct Array {     int A[10];    int size;    int length;}; // Function to print the array elementvoid Display(struct Array arr){    int i;     // Traverse the array arr[]    for (i = 0; i < arr.length; i++) {        cout <<" "<< arr.A[i];    }    cout <<"\n";} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){    // Store the value store at    // x in a variable temp    int temp = *x;     // Swapping of value    *x = *y;    *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront(    struct Array* arr, int key){    int i;     // Traverse the array    for (i = 0; i < arr->length; i++) {         // If key is found, then swap        // the element with 0-th index        if (key == arr->A[i]) {            swap(&arr->A[i], &arr->A[0]);            return i;        }    }    return -1;} // Driver codeint main(){    // Given array arr[]    struct Array arr        = { { 2, 23, 14, 5, 6, 9, 8, 12 },            10,            8 };     cout <<"Elements before Linear"           " Search Move To Front: ";     // Function Call for displaying    // the array arr[]    Display(arr);     // Function Call for Move to    // front operation    LinearSearchMoveToFront(&arr, 14);     cout <<"Elements after Linear"           " Search Move To Front: ";     // Function Call for displaying    // the array arr[]    Display(arr);    return 0;} // This code is contributed by shivanisinghss2110
// C program to implement the move to// front to optimized Linear Search#include <stdio.h> // Structure of the arraystruct Array {     int A[10];    int size;    int length;}; // Function to print the array elementvoid Display(struct Array arr){    int i;     // Traverse the array arr[]    for (i = 0; i < arr.length; i++) {        printf("%d ", arr.A[i]);    }    printf("\n");} // Function that swaps two elements// at different addressesvoid swap(int* x, int* y){    // Store the value store at    // x in a variable temp    int temp = *x;     // Swapping of value    *x = *y;    *y = temp;} // Function that performs the move to// front operation for Linear Searchint LinearSearchMoveToFront(    struct Array* arr, int key){    int i;     // Traverse the array    for (i = 0; i < arr->length; i++) {         // If key is found, then swap        // the element with 0-th index        if (key == arr->A[i]) {            swap(&arr->A[i], &arr->A[0]);            return i;        }    }    return -1;} // Driver codeint main(){    // Given array arr[]    struct Array arr        = { { 2, 23, 14, 5, 6, 9, 8, 12 },            10,            8 };     printf("Elements before Linear"           " Search Move To Front: ");     // Function Call for displaying    // the array arr[]    Display(arr);     // Function Call for Move to    // front operation    LinearSearchMoveToFront(&arr, 14);     printf("Elements after Linear"           " Search Move To Front: ");     // Function Call for displaying    // the array arr[]    Display(arr);    return 0;}
// Java program to implement// the move to front to optimized// Linear Searchclass GFG{ // Structure of the arraystatic class Array{  int []A = new int[10];  int size;  int length;  Array(int []A, int size,        int length)  {    this.A = A;    this.size = size;    this.length = length;  }}; // Function to print the// array elementstatic void Display(Array arr){  int i;   // Traverse the array arr[]  for (i = 0;       i < arr.length; i++)  {    System.out.printf("%d ", arr.A[i]);  }  System.out.printf("\n");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr,                                   int key){  int i;   // Traverse the array  for (i = 0; i < arr.length; i++)  {    // If key is found, then swap    // the element with 0-th index    if (key == arr.A[i])    {      int temp = arr.A[i];      arr.A[i] = arr.A[0];      arr.A[0] = temp;      return i;    }  }  return -1;} // Driver codepublic static void main(String[] args){  // Given array arr[]  int a[] = {2, 23, 14, 5,             6, 9, 8, 12 };  Array arr = new Array(a, 10, 8);   System.out.printf("Elements before Linear" +                    " Search Move To Front: ");   // Function Call for  // displaying the array  // arr[]  Display(arr);   // Function Call for Move  // to front operation  LinearSearchMoveToFront(arr, 14);   System.out.printf("Elements after Linear" +                    " Search Move To Front: ");   // Function Call for displaying  // the array arr[]  Display(arr);}} // This code is contributed by gauravrajput1
// C# program to implement// the move to front to optimized// Linear Searchusing System;class GFG{ // Structure of the arraypublic class Array{  public int []A = new int[10];  public int size;  public int length;  public Array(int []A,               int size,               int length)  {    this.A = A;    this.size = size;    this.length = length;  }}; // Function to print the// array elementstatic void Display(Array arr){  int i;   // Traverse the array []arr  for (i = 0;       i < arr.length; i++)  {    Console.Write(" " + arr.A[i]);  }  Console.Write("\n");} // Function that performs the// move to front operation for// Linear Searchstatic int LinearSearchMoveToFront(Array arr,                                   int key){  int i;   // Traverse the array  for (i = 0; i < arr.length; i++)  {    // If key is found, then swap    // the element with 0-th index    if (key == arr.A[i])    {      int temp = arr.A[i];      arr.A[i] = arr.A[0];      arr.A[0] = temp;      return i;    }  }  return -1;} // Driver codepublic static void Main(String[] args){  // Given array []arr  int []a = {2, 23, 14, 5,             6, 9, 8, 12 };     Array arr = new Array(a, 10, 8);  Console.Write("Elements before Linear" +                " Search Move To Front: ");   // Function Call for  // displaying the array  // []arr  Display(arr);   // Function Call for Move  // to front operation  LinearSearchMoveToFront(arr, 14);   Console.Write("Elements after Linear" +                " Search Move To Front: ");   // Function Call for displaying  // the array []arr  Display(arr);}} // This code is contributed by gauravrajput1
# Python3 program for transposition to# improve the Linear Search Algorithm  # Structure of the arrayclass Array :    def __init__(self,a=[0]*10,size=10,l=0) -> None:        self.A=a        self.size=size        self.length=l # Function to print array elementdef Display(arr):     # Traverse the array arr[]    for i in range(arr.length) :        print(arr.A[i],end=" ")         print()  # Function that performs the move to# front operation for Linear Searchdef LinearSearchMoveToFront(arr, key:int):     # Traverse the array    for i in range(arr.length) :         # If key is found, then swap        # the element with 0-th index        if (key == arr.A[i]) :            arr.A[i], arr.A[0]=arr.A[0],arr.A[i]            return i                  return -1  # Driver Codeif __name__ == '__main__':    # Given array arr[]    arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8)     print("Elements before Linear Search Transposition: ",end='')     # Function Call for displaying    # the array arr[]    Display(arr)     # Function Call for transposition    LinearSearchMoveToFront(arr, 14)     print("Elements after Linear Search Transposition: ",end='')     # Function Call for displaying    # the array arr[]    Display(arr)
Time Complexity: O(N)  Auxiliary Space: O(1)
princi singh
amit143katiyar
GauravRajput1
shivanisinghss2110
pankajsharmagfg
amartyaghoshgfg
khushboogoyal499
Algorithms-Searching
Algorithms
Arrays
Articles
Data Structures
Searching
Data Structures
Arrays
Searching
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
Find if there is a path between two vertices in an undirected graph
Arrays in Java
Multidimensional Arrays in Java
Arrays in C/C++
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Maximum and minimum of an array using minimum number of comparisons