Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
C++ Program to Sort the Elements of an Array in Ascending Order
Next article icon

C++ Program for Sorting all array elements except one

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. 


Examples: 

Input : arr[] = {10, 4, 11, 7, 6, 20}             k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20}  Input : arr[] = {30, 20, 10}          k = 0 Output : arr[] = {30, 10, 20} 

A simple solution is to copy all elements except k-th of a given array to another array. Then sort the other array using a sorting algorithm. Finally, again copy the sorted array to the original array. While copying, skip k-th element.
 

C++
// C++ code for the approach  #include <bits/stdc++.h> using namespace std;  // Function to sort an array in ascending order // except for the element at index k void sortExceptK(int arr[], int n, int k) {     int temp[n - 1], index = 0;     // Copy all elements except k-th to temp array     for (int i = 0; i < n; i++) {         if (i != k) {             temp[index++] = arr[i];         }     }      // Sort the temp array     sort(temp, temp + n - 1);      // Copy the sorted array back to original array     index = 0;     for (int i = 0; i < n; i++) {         if (i != k) {             arr[i] = temp[index++];         }     } }  // Driver code int main() {     int arr[] = { 10, 4, 11, 7, 6, 20 };     int k = 2;     int n = sizeof(arr) / sizeof(arr[0]);     // Function Call     sortExceptK(arr, n, k);      // Print final array     for (int i = 0; i < n; i++) {         cout << arr[i] << " ";     }      return 0; } 

Output
4 6 11 7 10 20 

Time Complexity: O(n*log2n) as sorting takes n*log2n time.

Space Complexity: O(n) as temp array has been created.

Below is an efficient solution.  

  1. Swap k-th element with the last element.
  2. Sort all elements except the last.
  3. For every element from (k+1)-th to last, move them one position ahead.1
  4. Copy k-th element back to position k. 
C++
// CPP program to sort all elements except // element at index k. #include <bits/stdc++.h> using namespace std;  int sortExceptK(int arr[], int k, int n) {     // Move k-th element to end     swap(arr[k], arr[n-1]);      // Sort all elements except last     sort(arr, arr + n - 1);      // Store last element (originally k-th)     int last = arr[n-1];      // Move all elements from k-th to one     // position ahead.     for (int i=n-1; i>k; i--)        arr[i] = arr[i-1];      // Restore k-th element     arr[k] = last; }  // Driver code int main() {     int a[] = {10, 4, 11, 7, 6, 20 };     int k = 2;     int n = sizeof(a) / sizeof(a[0]);     sortExceptK(a, k, n);     for (int i = 0; i < n; i++)         cout << a[i] << " "; } 

Output
4 6 11 7 10 20 

Time Complexity: O(n*log(n)) where n is the number of elements.
Auxiliary Space: O(1)

Please refer complete article on Sorting all array elements except one for more details!


Next Article
C++ Program to Sort the Elements of an Array in Ascending Order
author
kartik
Improve
Article Tags :
  • Sorting
  • C++ Programs
  • C++
  • DSA
  • Arrays
Practice Tags :
  • CPP
  • Arrays
  • Sorting

Similar Reads

  • C++ Program for Sorting array except elements in a subarray
    Given an array A positive integers, sort the array in ascending order such that element in given subarray (start and end indexes are input) in unsorted array stay unmoved and all other elements are sorted.Examples : Input : arr[] = {10, 4, 11, 7, 6, 20} l = 1, u = 3 Output : arr[] = {6, 4, 11, 7, 10
    2 min read
  • C++ Program for Last duplicate element in a sorted array
    We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
    2 min read
  • C++ Program to Sort the Elements of an Array in Ascending Order
    Here, we will see how to sort the elements of an array in ascending order using a C++ program. Below are the examples: Input: 3 4 5 8 1 10Output: 1 3 4 5 8 10 Input: 11 34 6 20 40 3Output: 3 6 11 20 34 40 There are 2 ways to sort an array in ascending order in C++: Brute-force Approach Using Bubble
    4 min read
  • C++ Program For Sorting An Array Of 0s, 1s and 2s
    Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples: Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0,
    6 min read
  • C++ Program to Find the Second Largest Element in an Array
    In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to find the second largest element in an array in C++. Examples: Input: arr[] = {34, 5, 16, 14, 56, 7, 56} Output: 34 Explanation: The
    3 min read
  • C++ Program for Search an element in a sorted and rotated array
    An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.  Exam
    7 min read
  • How Can I Efficiently Sort a Large Array in C++?
    In C++, sorting an array means rearranging the elements of an array in a logical order. In this article, we will learn how to efficiently sort a large array in C++. Example: Input: myArray = {5, 2, 3, 1, 4......};Output: Sorted array is : 1 2 3 4 5 ....Sorting a Very Large Array in C++ To efficientl
    2 min read
  • C++ Program to Sort String of Characters
    Sorting a string means rearranging the characters of the given string in some defined order such as alphabetical order. In this article, we will learn how to sort a string by characters in C++. Examples Input: str = "geeksforgeeks"Output: "eeeefggkkorss"Explanation: The characters in the string are
    4 min read
  • C++ Program for Check if an array is sorted and rotated
    Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
    5 min read
  • C/C++ Program for Odd-Even Sort / Brick Sort
    This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences