Program for K Most Recently Used (MRU) Apps in C++


Given a number k and an array arr[n], containing n number of integer elements which are storing the id’s of the opened apps in a system; the task is to show k number of most recently used apps, like when we press alt+tab shows all the recent apps and most recent before the least recent. The position of every id represents different apps in a system −

They are as follows −

  • Id in arr[0] is the id of an app which is currently in use.
  • Id in arr[1] is the id of an app which was most recently used.
  • Id in arr[n-1] is the id of an app which was least recently used.

Note − When we press Alt+Tab key there is a pointer, which moves through all the opened apps starting from index 0, the app which is currently in use.

Example

Input: arr[] = {1, 2, 3, 4, 5}, k=2
Output: 3 1 2 4 5
Explanation: We wished to switched the app with id 3, so it will become the currently
active app and other active apps will be the most recently used now

Input: arr[] = {6, 1, 9, 5, 3}, k=3
Output: 5 6 1 9 3

Approach we will be using to solve the above problem

  • Take an array arr[n] and k as an input.
  • Get the index i.e, k of the app which a user wants to switch.
  • Make the id at the index k as current and then arrange then as in they are in a order.
  • Print the result.

Algorithm

Start
Step 1-> declare the function to find k most recently used apps
   void recently(int* arr, int size, int elem)
   Declare int index = 0
   Set index = (elem % size)
   Declare and set int temp = index, id = arr[index]
   Loop While temp > 0
      Set arr[temp] = arr[--temp]
   End
   Set arr[0] = id
Step 2-> declare function to print array elements
   void print(int* arr, int size)
   Loop For i = 0 and i < size and i++
      Print arr[i]
   End
Step 3-> In main()
   Declare and set for elements as int elem = 3
   Declare array as int arr[] = { 6, 1, 9, 5, 3 }
   Calculate size as int size = sizeof(arr) / sizeof(arr[0])
   Call recently(arr, size, elem)
   Call print(arr, size)
Stop

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Function to update the array in most recently used fashion
void recently(int* arr, int size, int elem) {
   int index = 0;
   index = (elem % size);
   int temp = index, id = arr[index];
   while (temp > 0) {
      arr[temp] = arr[--temp];
   }
   arr[0] = id;
}
//print array elements
void print(int* arr, int size) {
   for (int i = 0; i < size; i++)
   cout << arr[i] << " ";
}
int main() {
   int elem = 3;
   int arr[] = { 6, 1, 9, 5, 3 };
   int size = sizeof(arr) / sizeof(arr[0]);
   recently(arr, size, elem);
   cout<<"array in most recently used fashion : ";
   print(arr, size);
   return 0;
}

Output

array in most recently used fashion : 5 6 1 9 3

Updated on: 23-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements