Ask a Question

 

Start Coding Today

   

GeeksQuiz

GeeksforGeeksIDE

Data Structures

Algorithms

Interview Experiences

C Programming

C++ Programming

Java Programming

GATE CS

Books

To sort an almost sorted array by swapping two elements causing discrepancy. Where is the problem in my code?

#include <iostream>

using namespace std;

int main()
{
   int size;
   cout<<"Enter the size of the array: \t";
   cin>>size;
   cout<<"Now enter the elements of the array: ";
   int arr[size];
   int i,j,k=2;
   int pos[k];
   for(int l=0;l<size;l++)
   {

    cin>>arr[l];
    cout<<"\n";
    }
   
   for(i=0;i<=(size-2);i++)
   {
      if(i==0)

      {
          if(arr[i+1]<arr[i])
          {
              pos[0]=i;
              k++;
          }
      }

      else if(i==(size-2))
              {
                  if(arr[size-1]<arr[size-2])
                {
                    pos[0]=i;
                    k++;
                }
              }

      else{
        if(((arr[i-1]<arr[i])&&(arr[i+1]<arr[i]))||((arr[i-1]>arr[i])&&(arr[i+1]>arr[i])))
        {
            pos[0]=i;
            k++;
            i=i+2;
        }
      }
   if(k>2)
   {
       break;
   }

   }

  int temp=arr[pos[0]];
  arr[pos[0]]=arr[pos[1]];
  arr[pos[1]]=temp;

  for(j=0;j<size;j++)
  {
      cout<<arr[j]<<"\t";
  }

   return 0;
}

asked Feb 2 by anonymous

Please log in or register to answer this question.

...