×

How to Sort an Array in C++

What is Sorting?

Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms, including bubble sort, insertion sort, selection sort, merge sort, quick sort, heap sort, etc. In this article, we will see to sort an array using Insertion sort and Selection sort.

1. Sorting an array using Selection sorting:

In a section sort, the smallest element in the array is repeatedly selected and substituted for the element at the beginning of the unsorted array to produce a sorted array.

Example for selection sorting:

#include<iostream>
using namespace std;
void selectionSort(int a[], int n) {
   int i, j, min, temp;
   for (i = 0; i < n - 1; i++) {
      min = i;
      for (j = i + 1; j < n; j++)
      if (a[j] < a[min])
      min = j;
      temp = a[i];
      a[i] = a[min];
      a[min] = temp;
   }
}
int main() {
   int a[] = { 1,44,55,79,12,25,60,39,100,49,69};
   int n = sizeof(a)/ sizeof(a[0]);
   int i;
   cout<<"User entered array is:"<<endl;
   for (i = 0; i < n; i++)
   cout<< a[i] <<" ";
   cout<<endl;
   selectionSort(a, n);
   printf("Sorted array is: \n");
   for (i = 0; i < n; i++)
   cout<< a[i] <<" ";
   return 0;
}

Output:

How to Sort an Array in C++

Explanation:

The above code is written to sort an array using a selection algorithm. In the above code, a function with the name selection sort() is created that is used to sort the array. We have used two loops in the selection sort() function. In every loop, the smallest element found is placed at the beginning of the array. In the main function, we call the function selectionsort(), and the output gets printed.

  • Example of Another method to sort the array:
#include <bits/stdc++.h>
using namespace std;


int main()
{
    int n;
    //taking input from the user using cout statement


    cout<<"Enter the size of array: "; cin>>n;


    int a[n];


    cout<<"\nEnter the elements: ";
    for(int i=0; i<n; i++) cin>>a[i];


//using for loop to sort the array and then print the new sorted array
    for(int i=0; i<n; i++)
    {
        for(int j=i+1; j<n; j++) { if(a[i]>a[j])
            {
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }


    cout<<"\nArray after swapping: ";


    for(int i=0; i<n; i++)
      cout<<a[i]<<" ";


    return 0;
}

Output:

How to Sort an Array in C++

Explanation:

In the above example, we have taken the input from the user to sort the array. Here user need to provide the array size and the array values for sorting. Then using the cout statement, we have printed the sorted array. In the main function we have declared two for loops for sorting. In one for loop we have compared all the elements with each other and then properly arranged them.

  • Sorting of an array using standard templet library
#include <bits/stdc++.h>


using namespace std;
int main()
{
    int arr[] = { 1,44,55,79,12,25,60,39,100,49,69};
    // Get size of array
    size_t len = sizeof(arr) / sizeof(arr[0]);
    // Calling sort() function from STL


    sort(arr, arr + len);
    // Printing Output
    cout<<"The sorted array is: ";
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout<<endl;
}

Output:

How to Sort an Array in C++

Explanation:

The above code is written to sort the array. Unlike the previous examples, we have used standard templet library’s pre-defined function sort(), which automatically sorts the given array. Then using the cout statement, we have printed the sorted array.

2. Sorting an array using Insertion sort

#include <iostream>
using namespace std;
void insertion_sort(int* arr, size_t len)
{
    int temp;
    // Assuming one element as sorted and inserting other elements into it
    for (int i = 1; i < len; i++)
    {
        temp = arr[i];
        // Finding the sorted position for the selected element in the sorted array and placing it.
        for (int j = i - 1; j >= 0; j--)
        {
            if (temp > arr[j])
            {
                arr[j + 1] = temp;
                break;
            }
            else if (temp <= arr[j])
            {
                arr[j + 1] = arr[j];
                if (j == 0)
                {
                    arr[j] = temp;
                }
            }
        }
    }
}
// Driver Code
int main()
{
    int arr[] = { 1,44,55,79,12,25,60,39,100,49,69};
    size_t len = sizeof(arr)/sizeof(arr[0]);
    // Calling insertion_sort function with given array
    insertion_sort(arr, len);
    // Printing Output
    cout << "The sorted Array is: ";
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";
    }
    cout<<endl;
}

Output:

How to Sort an Array in C++

Explanation:

A subarray is assumed to be sorted in the above code, and elements are added. In the beginning, only one element of the array is assumed to be sorted, and insetion_sort() implements the insertion sort.


Related Topics

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or...

4 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.