Count of elements which are not at the correct position
Given an array arr[] of N elements and the task is to count the number of elements from this array which are not at the correct position. An element is said to be in an incorrect position if its position changes in the array when the array is sorted.
Examples:
Input: arr[] = {1, 2, 6, 2, 4, 5}
Output: 4
Array in the sorted form will be {1, 2, 2, 4, 5, 6}
Input: arr[] = {1, 2, 3, 4}
Output: 0
All the elements are already sorted.
Approach: First copy the array elements in another array say B[] then sort the given array. Start traversing the array and for every element if arr[i] != B[i] then it is the element which was not at the right position in the given array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntElements( int arr[], int n)
{
int copy_arr[n];
for ( int i = 0; i < n; i++)
copy_arr[i] = arr[i];
int count = 0;
sort(arr, arr + n);
for ( int i = 0; i < n; i++) {
if (arr[i] != copy_arr[i]) {
count++;
}
}
return count;
}
int main()
{
int arr[] = { 1, 2, 6, 2, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << cntElements(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int cntElements( int arr[], int n)
{
int copy_arr[] = new int [n];
for ( int i = 0 ; i < n; i++)
copy_arr[i] = arr[i];
int count = 0 ;
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++)
{
if (arr[i] != copy_arr[i])
{
count++;
}
}
return count;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 6 , 2 , 4 , 5 };
int n = arr.length;
System.out.println(cntElements(arr, n));
}
}
|
Python3
def cntElements(arr, n) :
copy_arr = [ 0 ] * n
for i in range (n):
copy_arr[i] = arr[i]
count = 0
arr.sort()
for i in range (n):
if (arr[i] ! = copy_arr[i]) :
count + = 1
return count
arr = [ 1 , 2 , 6 , 2 , 4 , 5 ]
n = len (arr)
print (cntElements(arr, n))
|
C#
using System;
class GFG
{
static int cntElements( int [] arr, int n)
{
int [] copy_arr = new int [n];
for ( int i = 0; i < n; i++)
copy_arr[i] = arr[i];
int count = 0;
Array.Sort(arr);
for ( int i = 0; i < n; i++)
{
if (arr[i] != copy_arr[i])
{
count++;
}
}
return count;
}
public static void Main (String[] args)
{
int [] arr = { 1, 2, 6, 2, 4, 5 };
int n = arr.Length;
Console.WriteLine(cntElements(arr, n));
}
}
|
Javascript
<script>
function cntElements(arr, n) {
let copy_arr = new Array(n);
for (let i = 0; i < n; i++)
copy_arr[i] = arr[i];
let count = 0;
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
if (arr[i] != copy_arr[i]) {
count++;
}
}
return count;
}
let arr = [1, 2, 6, 2, 4, 5];
let n = arr.length;
document.write(cntElements(arr, n));
</script>
|
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Last Updated :
28 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...