Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Naive Partition Algorithm
Next article icon

Naive Partition Algorithm

Last Updated : 07 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], the task is to partition the array by assuming last element as pivot element.

The partition of an array must satisfy the following two conditions:

  • Elements smaller than or equal to the pivot element appear before pivot in the array.
  • Elements larger than the pivot element appear after pivot in the array.

Note: There might me more than one possible partition arrays.

Examples:

Input: arr[] = [5, 13, 6, 9, 12, 11, 8]
Output: [5, 6, 8, 13, 9, 12, 11]
Explanation: All elements smaller than pivot element [5, 6] were arranged before it and elements larger than pivot [13, 9, 12, 11] were arranged after it.

Input: arr[] = [4, 10, 9, 8, 16, 19, 9]
Output: [4, 9, 8, 9, 10, 16, 19]
Explanation: All elements smaller than or equal to pivot element [4, 9, 8] were arranged before it and elements larger than pivot [10, 16, 19] were arranged after it.

Table of Content

  • Naive approach to Partition an Array
  • Some Interesting Facts

Naive approach to Partition an Array

A simple approach to partition an array is to create a new temporary array which will store the rearranged elements. In this approach, we first iterate over the original array and add all elements that are smaller than or equal to the pivot to the temporary array. Then, we add the pivot element to the temporary array. Finally, we fill the remaining part of the temporary array with elements that are greater than the pivot.

This ensures that the smaller elements come before the pivot, and the larger elements come after it. Now, copy the elements from the temporary array back to the original array.

C++
// C++ program to partition the array // using naive partition approach #include <iostream> #include <vector> using namespace std;  // Function to partition the array according  // to pivot index element void partition(vector<int> &arr) {   	int n = arr.size();      	// Last element will be the pivot value   	int pivot = arr[n - 1];      	// create a temp array to store the elements in order   	vector<int> temp(n);   	int idx = 0;   	   	// First fill element smaller than or equal to   	// pivot, into the temp array   	for (int i = 0; i < n; i++) {       	if (arr[i] <= pivot)            	temp[idx++] = arr[i];     }   	   	// Now fill the elements greater than pivot   	for (int i = 0; i < n; i++) {       	if (arr[i] > pivot)            	temp [idx++] = arr[i];     }   	   	// copy the elements from temp to arr   	arr = temp; } int main() {     vector<int> arr = {5, 13, 6, 9, 12, 11, 8};   	partition(arr);   	   	for (int i = 0; i < arr.size(); i++)        	cout << arr[i] << " ";      return 0; } 
C
// C program to partition the array // using naive partition approach #include <stdio.h> #include <stdlib.h>  // Function to partition the array according  // to pivot index element void partition(int *arr, int n) {     // Last element will be the pivot value     int pivot = arr[n - 1];      // create a temp array to store the elements in order     int *temp = (int *)malloc(n * sizeof(int));     int idx = 0;          // First fill element smaller than or equal to     // pivot, into the temp array     for (int i = 0; i < n; i++) {         if (arr[i] <= pivot)              temp[idx++] = arr[i];     }          // Now fill the elements greater than pivot     for (int i = 0; i < n; i++) {         if (arr[i] > pivot)              temp[idx++] = arr[i];     }          // copy the elements from temp to arr     for (int i = 0; i < n; i++) {         arr[i] = temp[i];     }     free(temp); }  int main() {     int arr[] = {5, 13, 6, 9, 12, 11, 8};     int n = sizeof(arr) / sizeof(arr[0]);     partition(arr, n);          for (int i = 0; i < n; i++)          printf("%d ", arr[i]);      return 0; } 
Java
// Java program to partition the array // using naive partition approach import java.util.Arrays;  // Function to partition the array according  // to pivot index element class GfG {     static void partition(int[] arr) {         int n = arr.length;                // Last element will be the pivot value         int pivot = arr[n - 1];                // create a temp array to store the        	// elements in order         int[] temp = new int[n];         int idx = 0;                  // First fill element smaller than or        	// equal to pivot, into the temp array         for (int i = 0; i < n; i++) {             if (arr[i] <= pivot)                  temp[idx++] = arr[i];         }                  // Now fill the elements greater than pivot         for (int i = 0; i < n; i++) {             if (arr[i] > pivot)                  temp[idx++] = arr[i];         }                  // copy the elements from temp to arr         for (int i = 0; i < n; i++)            	arr[i] = temp[i];     }      public static void main(String[] args) {         int[] arr = {5, 13, 6, 9, 12, 11, 8};         partition(arr);              	for (int ele: arr)         	System.out.print(ele + " ");     } } 
Python
# Function to partition the array according  # to pivot index element def partition(arr):     n = len(arr)          # Last element will be the pivot value     pivot = arr[n - 1]          # create a temp array to store      # the elements in order     temp = [0] * n     idx = 0          # First fill elements smaller than or equal to     # pivot, into the temp array     for i in range(n):         if arr[i] <= pivot:             temp[idx] = arr[i]             idx += 1          # Now fill the elements greater than pivot     # into the temp array     for i in range(n):         if arr[i] > pivot:             temp[idx] = arr[i]             idx += 1          # copy the elements from temp to arr     for i in range(n):         arr[i] = temp[i]  if __name__ == "__main__":     arr = [5, 13, 6, 9, 12, 11, 8]     partition(arr)          for ele in arr:     	print(ele, end = ' ') 
C#
// C# program to partition the array // using naive partition approach using System; class GfG {        // Function to partition the array according      // to pivot index element     static void Partition(int[] arr) {         int n = arr.Length;                // Last element will be the pivot value         int pivot = arr[n - 1];                // create a temp array to store the elements        	// in order         int[] temp = new int[n];         int idx = 0;                  // First fill element smaller than or equal to         // pivot, into the temp array         for (int i = 0; i < n; i++) {             if (arr[i] <= pivot)                  temp[idx++] = arr[i];         }                  // Now fill the elements greater than pivot         for (int i = 0; i < n; i++) {             if (arr[i] > pivot)                  temp[idx++] = arr[i];         }                  // copy the elements from temp to arr         Array.Copy(temp, arr, n);     }      static void Main() {         int[] arr = {5, 13, 6, 9, 12, 11, 8};         Partition(arr);         Console.WriteLine(string.Join(" ", arr));     } } 
JavaScript
// JavaScript program to partition the array // using naive partition approach  // Function to partition the array according  // to pivot index element function partition(arr) {     let n = arr.length;          // Last element will be the pivot value     let pivot = arr[n - 1];          // create a temp array to store the      // elements in order     let temp = new Array(n);     let idx = 0;          // First fill element smaller than or equal to     // pivot, into the temp array     for (let i = 0; i < n; i++) {         if (arr[i] <= pivot)              temp[idx++] = arr[i];     }          // Now fill the elements greater than pivot     for (let i = 0; i < n; i++) {         if (arr[i] > pivot)              temp[idx++] = arr[i];     }          // copy the elements from temp to arr     for (let i = 0; i < n; i++) {         arr[i] = temp[i];     } }  // Driver Code let arr = [5, 13, 6, 9, 12, 11, 8]; partition(arr); console.log(arr.join(' ')); 

Output
5 6 8 13 9 12 11 

Time Complexity: O(n), for array traversal
Auxiliary Space: O(n), As it uses a temporary array

Some Interesting Facts

  • It is a stable partitioning algorithm, meaning it preserves the relative order of duplicate elements. We can make Quick Sort stable by using it
  • It is slower than other partitioning algorithms because it requires multiple traversals of the array and uses extra space for storing elements.
  • We can easily modify the algorithm to consider the first element (or any other element) as pivot by swapping first and last elements and then using the same code.



Next Article
Naive Partition Algorithm

A

anugum2xzm
Improve
Article Tags :
  • Sorting
  • DSA
  • Arrays
  • Quick Sort
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

    Partition Algorithms - Complete Tutorial
    Partition algorithms are key techniques in computer science, widely used in sorting (like QuickSort) and selection problems. By dividing an array around a pivot, they allow data to be organized into segments for faster sorting and searching. This tutorial covers popular partitioning methods, includi
    3 min read
    Searching Algorithms
    Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
    3 min read
    Analysis of Algorithms
    Analysis of Algorithms is a fundamental aspect of computer science that involves evaluating performance of algorithms and programs. Efficiency is measured in terms of time and space.Basics on Analysis of Algorithms:Why is Analysis Important?Order of GrowthAsymptotic Analysis Worst, Average and Best
    1 min read
    Bitwise Algorithms
    Bitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
    4 min read
    Introduction to Divide and Conquer Algorithm
    Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. Divide and Conquer is mainly useful when we divide a problem into independent su
    9 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