Check if a Linked List is Pairwise Sorted in C++

C++Server Side ProgrammingProgramming

We have a list L, with n elements. We have to check whether the list is pairwise sorted or not. Suppose the list is like {8, 10, 18, 20, 5, 15}. This is pairwise sorted as (8, 10), (18, 20), (5, 15) are sorted. If the list has odd number of elements, then last one will be ignored.

The approach is too simple, traverse the number from left to right. Two consecutive elements are taken, and check whether they are sorted or not, if any one pair is not sorted, return false, if no pair is found, that is unsorted, return true.

Example

Live Demo

#include <iostream>
#include <cmath>
using namespace std;
class Node{
   public:
   int data;
   Node *next;
};
void append(struct Node** start, int key) {
   Node* new_node = new Node;
   new_node->data = key;
   new_node->next = (*start);
   (*start) = new_node;
}
bool isPairwiseSorted(Node *start) {
   bool flag = true;
   struct Node* temp = start;
   while (temp != NULL && temp->next != NULL) {
      if (temp->data < temp->next->data) {
         flag = false;
         break;
      }
      temp = temp->next->next;
   }
   return flag;
}
int main() {
   Node *start = NULL;
   int arr[] = {8, 10, 18, 20, 5, 15};
   int n = sizeof(arr)/sizeof(arr[0]);
   for(int i = 0; i<n; i++){
      append(&start, arr[i]);
   }
   if(isPairwiseSorted(start)){
      cout << "This is pairwise sorted";
   } else {
      cout << "This is not pairwise sorted";
   }
}

Output

This is pairwise sorted
raja
Published on 22-Oct-2019 15:01:45
Advertisements