sorting algorithms c++ code example

Example 1: stl for sorting IN C++

// STL IN C++ FOR SORING
#include <bits/stdc++.h> 
#include <iostream> 
using namespace std; 
int main() 
{ 
    int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    sort(arr, arr+n);  // ASCENDING SORT
    reverse(arr,arr+n);   //REVERESE ARRAY 
    sort(arr, arr + n, greater<int>());// DESCENDING SORT
  }

Example 2: C++ sorting array

#include <iostream>
using namespace std;

#define MAX 100

int main()
{
	//array declaration
	int arr[MAX];
	int n,i,j;
	int temp;
	
	//read total number of elements to read
	cout<<"Enter total number of elements to read: ";
	cin>>n;
	
	//check bound
	if(n<0 || n>MAX)
	{
		cout<<"Input valid range!!!"<<endl;
		return -1;
	}
	
	//read n elements
	for(i=0;i<n;i++)
	{
		cout<<"Enter element ["<<i+1<<"] ";
		cin>>arr[i];
	}
	
	//print input elements
	cout<<"Unsorted Array elements:"<<endl;
	for(i=0;i<n;i++)
		cout<<arr[i]<<"\t";
	cout<<endl;
	
	//sorting - ASCENDING ORDER
	for(i=0;i<n;i++)
	{		
		for(j=i+1;j<n;j++)
		{
			if(arr[i]>arr[j])
			{
				temp  =arr[i];
				arr[i]=arr[j];
				arr[j]=temp;
			}
		}
	}
	
	//print sorted array elements
	cout<<"Sorted (Ascending Order) Array elements:"<<endl;
	for(i=0;i<n;i++)
		cout<<arr[i]<<"\t";
	cout<<endl;	
	
	
	return 0;
	
}

Example 3: sort algorithms java

for (int i = 0; i < arr.length; i++) {
   for (int j = 0; j < arr.length-1-i; j++) { 
     if(arr[j]>arr[j+1])
     {
       int temp=arr[j];
       arr[j]=arr[j+1];
       arr[j+1]=temp;
     }
   }
   System.out.print("Iteration "+(i+1)+": ");
   printArray(arr);
  }
  return arr;
// BUBBLE SORT

Example 4: sorting algorithm c++

#include<iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    int numb[7];
    int i, j;

    for(i=0;i<=6;i++)
    {
        cout << "Enter a number" << endl;
        cin >> numb[i];
    }

    for (i=0;i<=5;i++)
    {
        for (j=i+1;j<=5;j++)
        {
            int temp;

            if (numb[i] > numb[j])
            {
                temp = numb[i];
                numb[i] = numb[j];
                numb[j] = temp;               
            }
          }
        }
        for (i=0;i<=6;i++)
        {
            cout << endl << numb[i] << endl;
        }
}

Example 5: sorting in data structure

A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective data structure.

Tags:

C Example