Sort an Array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers; we have to sort them in ascending order. So if the array is like [5,2,3,1], then the result will be [1,2,3,5]

To solve this, we will follow these steps −

  • Make one method called partition, this will take array, low and high

  • set pivot := low

  • for i in range low to high – 1

    • if nums[i] < nums[high], then swap(nums[i] and nums[pivot]), increase pivot by 1

  • swap nums[pivot] and nums[high]

  • Define a method called sortArr(), this will take array, low and high

  • if low >= high, then return

  • partitionIndex := partition(nums, low, high)

  • sortArr(nums, low, partitionIndex – 1)

  • sortArr(nums, partitionIndex + 1, high)

  • call the sortArr() from main method by passing low and high as 0 and size of arr – 1

Let us see the following implementation to get better understanding −

Example

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   int partition(vector <int>& nums, int low, int high){
      int pivot = low;
      for(int i = low; i < high; i++){
         if(nums[i] < nums[high]){
            swap(nums[i], nums[pivot]);
            pivot++;
         }
      }
      swap(nums[pivot], nums[high]);
      return pivot;
   }
   void sortArr(vector <int>& nums, int low, int high){
      if(low >= high) return;
      int partitionIndex = partition(nums, low, high);
      sortArr(nums, low, partitionIndex - 1);
      sortArr(nums, partitionIndex + 1, high);
   }
   vector<int> sortArray(vector<int>& nums) {
      sortArr(nums, 0, nums.size() - 1);
      return nums;
   }
};
main(){
   vector<int> v1 = {5,2,3,1};
   Solution ob;
   print_vector(ob.sortArray(v1));
}

Input

[5,2,3,1]

Output

[1,2,3,5]
raja
Published on 10-Apr-2020 10:04:17
Advertisements