Sortings
Bubble Sort in C++
#include <conio.h>
#include <malloc.h>
void bubble_sort(int a[], int n);
void main()
{
int i,n;
int* a;
clrscr();
cout << "Enter the no. of elements:";
cin >> n;
a = (int*) malloc(sizeof(int)*n); //dynamic array declearation
cout << "\nEnter the elements :\n\n";
for(i = 0; i < n; i++)
{
cin >> a[i];
}
bubble_sort(a, n);
cout << "\nSorted array is: ";
for(i = 0; i < n; i++)
{
cout << a[i] << " ";
}
getch();
}
void bubble_sort(int a[], int n)
{
int i,j,temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
Selection sort
#include <iostream.h>
#include <conio.h>
#include <malloc.h>
void selection_sort(int a[],int n); //Prototype of the calling function..
void main()
{
int i,n;
int* a;
clrscr();
cout << "Enter the no of elements: ";
cin >> n;
a = (int*) malloc(sizeof(int)*n);
cout << "\nEnter the elements:\n\n";
for(i = 0; i < n; i++)
{
cin >> a[i];
}
selection_sort(a,n);
cout << "\nSorted array is:\n\n";
for(i = 0; i < n; i++)
{
cout << "\t" << a[i] << "\n" ;
}
getch();
}
void selection_sort(int a[],int n)
{
int i,j,temp,loc,min;
for(i = 0; i < n; i++)
{
min = a[i];
loc = i;
for(j = i+1; j < n; j++)
{
if(a[j] < min)
{
min = a[j];
loc = j;
}
}
if(loc != i)
{
temp = a[i];
a[i] = a[loc];
a[loc] = temp;
}
}
}
Printing SomeRamnjanNubers In C
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,k,l,n=40,a,b,c,d;
for(i=1;i<n;i++)
{
for(j=i+1;j<n;j++)
{
for(k=i+1;k<n;k++)
{
for(l=k+1;l<n;l++)
{
a=(i*i*i);
b=(j*j*j);
c=(k*k*k);
d=(l*l*l);
if((a+b)==(c+d))
{
if(a!=b && b!=c && c!=d && a!=c && a!=d && b!=d)
{
printf("%3d=",(a+b));
printf(" %3d ^3 ",i);
printf("%3d",j);
printf("%3d",k);
printf("%3d",l);
printf("\n");
}
}
}
}
}
}
getch();
}
No comments:
Post a Comment