Tuesday, 21 March 2017

Insertion Sort in C++.

C++ CODE
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    int a[10], i, j, k, temp;
    cout<<"enter the elements\n";
    for (i = 0; i < 10; i++)
    {
        cin>>a[i];
    }
    for (i = 1; i < 10; i++)
    {
        for (j = i; j >= 1; j--)
        {
            if (a[j] < a[j-1])
            {
                temp = a[j];
                a[j] = a[j-1];
                a[j-1] = temp;
            }
            else
                break;
        }
    }
    cout<<"sorted array\n"<<endl;
    for (k = 0; k < 10; k++)
    {
cout<<a[k]<<" ";
    }
    getch();

}

Selection Sorting in C++.

C++ Code
#include <iostream>
using namespace std;

void print (int [], int);
void selection_sort (int [], int);

//Driver Function
int main ()
{
  int ar[] = {10, 2, 45, 18, 16, 30, 29, 1, 1, 100};
  cout << "Array initially : ";
  print (ar, 10);
  selection_sort (ar, 10);
  cout << "Array after selection sort : ";
  print (ar, 10);
  return 0;
}

// Selection Sort
void selection_sort (int ar[], int size)
{
  int min_ele_loc;
  for (int i = 0; i < 9; ++i)
  {
    //Find minimum element in the unsorted array
    //Assume it's the first element
    min_ele_loc = i;

    //Loop through the array to find it
    for (int j = i + 1; j < 10; ++j)
    {
      if (ar[j] < ar[min_ele_loc])
      {
        //Found new minimum position, if present
        min_ele_loc = j;
      }
    }

    //Swap the values
    swap (ar[i], ar[min_ele_loc]);
  }
}

//Print the array
void print (int temp_ar[], int size)
{
  for (int i = 0; i < size; ++i)
  {
    cout << temp_ar[i] << " ";
  }
  cout << endl;
}

If you want to take values from the user then....!

int main ()
{
  int n=10;
  int ar[n];
  for (int i = 0,j=1; i < n,j<=10; i++,j++)
  {
  cout<<"Enter your number "<<j<<"=";
    cin>>ar[i];
  }
  cout << "Array initially : ";
  print (ar, n);
  selection_sort (ar, n);
  cout << "Array after selection sort : ";
  print (ar, n);
  return 0;
}

Bubble Sorting in C++.

C++ CODE


#include <iostream>
using namespace std;

void bubble_sort (int arr[], int n)
 {
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n - i - 1;j++)
      if (arr[j] > arr[j + 1])
     {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
  }

int main()
{
  int n = 10;
  int input_ar[n] = {10, 50, 21, 2, 6, 66, 802, 75, 24, 170};
  bubble_sort (input_ar, n);
  cout << "Sorted Array : " << endl; 
  for (int i = 0; i < n; i++)
    cout << input_ar[i] << " ";
  return 0;
}

If you want to take values from the user then......!

int main()
{
  int n = 10;
  int input_ar[n];
  for(int i=0,j=1;i<10,j<=10;i++,j++)
  {
  cout<<"Enter your number "<<j<<"=";
  cin>>input_ar[i];
  }
  bubble_sort (input_ar, n);
  cout << "Sorted Array : " << endl; 
  for (int i = 0; i < n; i++)
    cout << input_ar[i] << " ";
  return 0;
}