×

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

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

How to Reverse a String in C++ using Do-While Loop

Strings In C++, a string is an object that represents a group (or sequence) of various characters. Strings are part of the standard string class in C++ (std::string). The characters of...

4 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.