You are on page 1of 8

Insertion sort

#include <iostream>

using namespace std;

int main()

int n,i;

cout<<"\nEnter the no of elements ";

cin>>n;

int num[n];

cout<<"\nEnter elements ";

for(i=0;i<n;i++)

cin>>num[i];

int j,x;

cout<<"Array before Insertion Sort"<<endl;

for(i=0; i<n; i++)

cout<<num[i]<<" ";

for(i=1; i<n ; i++)

x=num[i];

j=i-1;

while(j>=0)

{
if(x<num[j])

num[j+1]=num[j];

else

break;

j=j-1;

num[j+1]=x;

cout<<"\n\nArray after Insertion Sort\n";

for(i=0; i<n; i++)

cout<<num[i]<<" ";

}
Bubble sort

#include<iostream>

using namespace std;

int main()

int n, i, arr[50], j, temp;

cout<<"Enter the Size (max. 50): ";

cin>>n;

cout<<"Enter "<<n<<" Numbers: ";

for(i=0; i<n; i++)

cin>>arr[i];

cout<<"\nSorting the Array using Bubble Sort Technique..\n";

for(i=0; i<(n-1); i++)

for(j=0; j<(n-i-1); j++)

if(arr[j]>arr[j+1])

temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

cout<<"\nArray Sorted Successfully!\n";

cout<<"\nThe New Array is: \n";


for(i=0; i<n; i++)

cout<<arr[i]<<" ";

cout<<endl;

return 0;

}
Radix sort
#include<iostream>

using namespace std;

int getMax(int array[], int n)

int max = array[0];

for (int i = 1; i < n; i++) if (array[i] > max)

max = array[i];

return max;

void countSort(int array[], int size, int place)

const int max = 10;

int output[size];

int count[max];

for (int i = 0; i < max; ++i)

count[i] = 0;

for (int i = 0; i < size; i++)

count[(array[i] / place) % 10]++;

for (int i = 1; i < max; i++)

count[i] += count[i - 1];

for (int i = size - 1; i >= 0; i--)

output[count[(array[i] / place) % 10] - 1] = array[i];

count[(array[i] / place) % 10]--;

for (int i = 0; i < size; i++)

array[i] = output[i];

void radixsort(int array[], int size)


{

int max = getMax(array, size);

for (int place = 1; max / place > 0; place *= 10)

countSort(array, size, place);

void display(int array[], int size)

int i;

for (i = 0; i < size; i++)

cout << array[i] << "\t";

cout << endl;

int main()

int array[] = {220, 100, 503, 341, 778, 975, 0, 770};

int n = sizeof(array) / sizeof(array[0]);

cout<<"Before sorting \n";

display(array, n);

radixsort(array, n);

cout<<"After sorting \n";

display(array, n);

}
Selection sort
#include<iostream>

using namespace std;

void swapping(int &a, int &b) {

int temp;

temp = a;

a = b;

b = temp;

void display(int *array, int size) {

for(int i = 0; i<size; i++)

cout << array[i] << " ";

cout << endl;

void selectionSort(int *array, int size) {

int i, j, imin;

for(i = 0; i<size-1; i++) {

imin = i;

for(j = i+1; j<size; j++)

if(array[j] < array[imin])

imin = j;

swap(array[i], array[imin]);

int main() {

int n;

cout << "Enter the number of elements: ";

cin >> n;

int arr[n];

cout << "Enter elements:" << endl;


for(int i = 0; i<n; i++) {

cin >> arr[i];

cout << "Array before Sorting: ";

display(arr, n);

selectionSort(arr, n);

cout << "Array after Sorting: ";

display(arr, n);

You might also like