Improving Linear Search Technique

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: 

  1. Transposition
  2. Move to Front

Transposition:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program for transposition to
// improve the Linear Search Algorithm
#include <stdio.h>
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void 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 addresses
void 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 Transposition
int 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 Code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for transposition
// to improve the Linear Search
// Algorithm
class GFG{
 
// Structure of the
// array
static 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 element
static 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 Transposition
static 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 Code
public 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for transposition
// to improve the Linear Search
// Algorithm
using System;
 
class GFG{
 
// Structure of the
// array
public 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 element
static 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 Transposition
static 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 Code
public 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

chevron_right


Output: 
Elements before Linear Search Transposition: 2 23 14 5 6 9 8 12 
Elements after Linear Search Transposition: 2 14 23 5 6 9 8 12 
 

Move to Front/Head:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to implement the move to
// front to optimized Linear Search
#include <stdio.h>
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void 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 addresses
void 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 Search
int 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 code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the move to front to optimized
// Linear Search
class GFG{
 
// Structure of the array
static 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 element
static 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 Search
static 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 code
public 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the move to front to optimized
// Linear Search
using System;
class GFG{
 
// Structure of the array
public 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 element
static 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 Search
static 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 code
public 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

chevron_right


Output: 
Elements before Linear Search Move To Front: 2 23 14 5 6 9 8 12 
Elements after Linear Search Move To Front: 14 23 2 5 6 9 8 12
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.