0% found this document useful (0 votes)
176 views32 pages

Asses Ement 3

The document contains code snippets for several algorithms and data structures including: 1) A merge sort algorithm that splits an array, recursively sorts the halves, and then merges the sorted halves. 2) Code for insertion sort, bubble sort, and linear search algorithms. 3) A binary search algorithm that recursively searches a sorted array by checking the middle element and adjusting the search range. 4) Code examples for other algorithms including strong number determination, GCD calculation, palindrome checking, number reversing, Armstrong number checking, and factorial calculation.

Uploaded by

Nikhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
176 views32 pages

Asses Ement 3

The document contains code snippets for several algorithms and data structures including: 1) A merge sort algorithm that splits an array, recursively sorts the halves, and then merges the sorted halves. 2) Code for insertion sort, bubble sort, and linear search algorithms. 3) A binary search algorithm that recursively searches a sorted array by checking the middle element and adjusting the search range. 4) Code examples for other algorithms including strong number determination, GCD calculation, palindrome checking, number reversing, Armstrong number checking, and factorial calculation.

Uploaded by

Nikhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 32

#include <iostream>

using namespace std;

// A function to merge the two half into a sorted data.


void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

// Merge the two parts into temp[].


while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}

// Insert all the remaining values from i to mid into temp[].


while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}

// Insert all the remaining values from j to high into temp[].


while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}

// Assign sorted data stored in temp[] to a[].


for (i = low; i <= high; i++)
{
a[i] = temp[i-low];
}
}

// A function to split array into two parts.


void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);

// Merge them to get sorted output.


Merge(a, low, high, mid);
}
}

int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}

MergeSort(arr, 0, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];

return 0;
}

insertion

#include <stdio.h>
#include <math.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}

bubble

#include<iostream>

using namespace std;

int main()
{
int a[50],n,i,j,temp;
cout<<"Enter the size of array: ";
cin>>n;
cout<<"Enter the array elements: ";

for(i=0;i<n;++i)
cin>>a[i];

for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

cout<<"Array after bubble sort:";


for(i=0;i<n;++i)
cout<<" "<<a[i];

return 0;
}
Linear

#include<iostream>

using namespace std;

int main()
{
int a[20],n,x,i,flag=0;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter elements of the array\n";

for(i=0;i<n;++i)
cin>>a[i];

cout<<"\nEnter element to search:";


cin>>x;

for(i=0;i<n;++i)
{
if(a[i]==x)
{
flag=1;
break;
}
}

if(flag)
cout<<"\nElement is found at position "<<i+1;
else
cout<<"\nElement not found";

return 0;
}

binary

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, arr[50], search, first, last, middle;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" number :";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;

}
else if(arr[middle] == search)
{
cout<<search<<" found at location "<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the list.";
}
getch();
}

Strong Number

To find Strong Number


import java.util.scanner;
public class strongnumber
{
public static void
main(string args[])
{
strongnumber ss=new
strongnumber();
int a,b,r,s=0;
scanner sl=new scanner(system.in);
system.out.println(�Enter a number�);
b=sl.nextInt();
a=b;
while(b>0)
{
r=b%10;
s=s+ss.fact(r);
b=b/10;
}
if(a==s)
system.out.println(a+� is a stong number);
else
system.out.println(a+�is not a strong number);
}
int fact(int i)
{
int f,j;
f=1;
for(j=i;j>0;j--)
f=f*j;
return f;
}
}
GCD of Two Numbers:
import java.util.P;
public class gcdoftwonumbers
{
public static void
main(string args[])
{
int a,b,gcd;
a=b=gcd=0;
scanner s=new scanner(system.in);
system.out.println(�enter two num);
a=s.nextInt();
b=s.next.Int();
while(a!=0)
{
gcd=a;
a=b%a;
b=gcd;
}
system.out.println(�GCD�+gcd);
}
}

Palindrome

import java.util.*;

class Palindrome
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome");


original = in.nextLine();

int length = original.length();

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


reverse = reverse + original.charAt(i);

if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string isn't a palindrome.");

}
}

Reverse

import java.util.Scanner;

class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;

System.out.println("Enter a number to reverse");


Scanner in = new Scanner(System.in);
n = in.nextInt();

while(n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

System.out.println("Reverse of the number is " + reverse);


}
}

Reverse String

import java.util.*;

class ReverseString
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to reverse");


original = in.nextLine();

int length = original.length();

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


reverse = reverse + original.charAt(i);

System.out.println("Reverse of entered string is: "+reverse);


}
}

Armstrong Number

import java.util.Scanner;

class ArmstrongNumber
{
public static void main(String args[])
{
int n, sum = 0, temp, remainder, digits = 0;

Scanner in = new Scanner(System.in);


System.out.println("Input a number to check if it is an Armstrong number");

n = in.nextInt();
temp = n;

// Count number of digits

while (temp != 0) {
digits++;
temp = temp/10;
}

temp = n;

while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}

if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " isn't an Armstrong number.");
}

static int power(int n, int r) {


int c, p = 1;

for (c = 1; c <= r; c++)


p = p*n;

return p;
}
}

Factorial

import java.util.Scanner;

class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;

System.out.println("Enter an integer to calculate it's factorial");


Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println("Number should be non-negative.");
else
{
for (c = 1; c <= n; c++)
fact = fact*c;

System.out.println("Factorial of "+n+" is = "+fact);


}
}
}

Swap without Temp

import java.util.Scanner;

class SwapNumbers
{
public static void main(String args[])
{
int x, y;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);

x = in.nextInt();
y = in.nextInt();

System.out.println("Before Swapping\nx = "+x+"\ny = "+y);

x = x + y;
y = x - y;
x = x - y;

System.out.println("After Swapping\nx = "+x+"\ny = "+y);


}
}

Swap

import java.util.Scanner;

class SwapNumbers
{
public static void main(String args[])
{
int x, y, temp;
System.out.println("Enter x and y");
Scanner in = new Scanner(System.in);

x = in.nextInt();
y = in.nextInt();

System.out.println("Before Swapping\nx = "+x+"\ny = "+y);

temp = x;
x = y;
y = temp;

System.out.println("After Swapping\nx = "+x+"\ny = "+y);


}
}

Multiplication Table

import java.util.Scanner;
class MultiplicationTable
{
public static void main(String args[])
{
int n, c;
System.out.println("Enter an integer to print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of "+n+" is :-");

for ( c = 1 ; c <= 10 ; c++ )


System.out.println(n+"*"+c+" = "+(n*c));
}
}

Sort and Search in Java

Ascending order:

1. import java.util.Scanner;
2. public class Ascending _Order
3. {
4. public static void main(String[] args)
5. {
6. int n, temp;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter no. of elements you want in array:");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter all the elements:");
12. for (int i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. for (int i = 0; i < n; i++)
17. {
18. for (int j = i + 1; j < n; j++)
19. {
20. if (a[i] > a[j])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. System.out.print("Ascending Order:");
29. for (int i = 0; i < n - 1; i++)
30. {
31. System.out.print(a[i] + ",");
32. }
33. System.out.print(a[n - 1]);
34. }
35. }

bubble sort:(ascending order)


import java.util.Scanner;

class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

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


array[i] = input.nextInt();

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


for (j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}

System.out.println("Sorted list of integers:");

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


System.out.println(array[i]);
}
}

bubble sort:(descending order)


import java.util.Scanner;

class BubbleSortExample {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

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


array[i] = input.nextInt();

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


for (j = 0; j < num - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}

System.out.println("Sorted list of integers:");

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


System.out.println(array[i]);
}
}

INSERTION SORT:
// Java program for implementation of Insertion Sort
class InsertionSort
{
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

/* A utility function to print array of size n*/


static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6};

InsertionSort ob = new InsertionSort();


ob.sort(arr);

printArray(arr);
}
} /* This code is contributed by Rajat Mishra. */
MERGE SORT:
/* Java program for Merge Sort */
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int [n1];
int R[] = new int [n2];

/*Copy data to temp arrays*/


for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarry array


int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy remaining elements of L[] if any */


while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy remaining elements of R[] if any */


while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

// Main function that sorts arr[l..r] using


// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;

// Sort first and second halves


sort(arr, l, m);
sort(arr , m+1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

/* A utility function to print array of size n */


static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};

System.out.println("Given Array");
printArray(arr);

MergeSort ob = new MergeSort();


ob.sort(arr, 0, arr.length-1);

System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */

SEARCHING:
LINEAR SEARCH:
import java.util.Scanner;

class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter " + n + " integers");

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


array[c] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

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


{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}

BINARY SEARCH:
// Java implementation of recursive Binary Search
class BinarySearch
{
// Returns index of x if it is present in arr[l..
// r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r - l)/2;

// If the element is present at the


// middle itself
if (arr[mid] == x)
return mid;

// If element is smaller than mid, then


// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);

// Else the element can only be present


// in right subarray
return binarySearch(arr, mid+1, r, x);
}

// We reach here when element is not present


// in array
return -1;
}

// Driver method to test above


public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = {2,3,4,10,40};
int n = arr.length;
int x = 10;
int result = ob.binarySearch(arr,0,n-1,x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " +
result);
}
}
/* This code is contributed by Rajat Mishra */

Programs:
1. Implement Recursive Binary search and Linear search and determine the time
required to search an element. Repeat the experiment for different values of n, the
number of elements in the list to be searched and plot a graph of the time taken
versus
n.
#include<stdio.h>
#include<conio.h
#include<time.h>
void main()
{
int i,n,a[10],low,high,ch,mid,key,x;
clock_t start,end;
float b;
clrscr();
do
{
printf(" \n ***Menu***");
printf("\n 1.Linear search 2.Binary serach 3.Exit");
printf("\n Enter your choice:")

scanf("%d",&ch);
switch(ch)
{
case 1:
start=clock();
printf("Enter the size of the array:");
scanf("%d",&n);
printf("Enter the elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element to be searched:");
scanf("%d",&key);
x=lsearch(a,n,key);
end=clock();
b=(end-start)/CLOCKS_PER_SEC;
if(x<0)
printf("Search unsuccessful\n");
else
printf("Search successful\n");
printf("The running time is:%f",b);
break;
case 2:
start=clock();
printf("Enter the size of the array:");
scanf("%d",&n);
printf("Enter the elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element to be searched:");
scanf("%d",&key);
low=0;
high=n-1;
x=bsearch(a,n,key,low,high);
end=clock();
b=(end-start)/CLOCKS_PER_SEC;
if(x<0)
printf("Search unsuccessful\n");
else
printf("\nSearch successful\n");
printf("The running time is:%f",b);
break;
case 3: exit(0);
break;
}
}while(ch!=3);
getch();
}
int lsearch(int a[],int n,int key)
{
if(n<0)
return(-1);
if(a[n-1]==key)
return(n);
else
return(lsearch (a,n-1,key));
}
int bsearch(int a[],int n,int key,int low,int high)
{
int mid;
if(low>high)
return(-1);
mid=(low+high)/2;
if(key==a[mid])
return (mid);
if(key<a[mid])
bsearch(a,n,key,low,mid-1);
else
bsearch(a,n,key,mid+1,high);
}

2. Sort a given set of elements using the Heap sort method and determine the time
required to sort the elements. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken
versus
n.
#include<stdio.h>
#include<conio.h>
#include<time.h>
void heapsort(int[],int);
void heapify(int[],int);
void adjust(int[],int);
void main()
{
int n,i,a[50];
float p;
clock_t start,end;
clrscr();
start=clock();
printf("\nEnter the size of the array:");
scanf("%d",&n);
printf("\nEnter the elements:");
for (i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
end=clock();
p=(end-start)/CLOCKS_PER_SEC;
printf("\nThe Sorted Elements are:");
for (i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\nThe running time is: %2.3f\n",p);
getch();
}
void heapsort(int a[],int n)
{
int i,t;
heapify(a,n);
for (i=n-1;i>0;i--)
{
t = a[0];
a[0] = a[i];
a[i] = t;
adjust(a,i);
}
}
void heapify(int a[],int n)
{
int k,i,j,item;
for (k=1;k<n;k++)
{
item = a[k];
i = k;
j = (i-1)/2;
while((i>0)&&(item>a[j]))
{
a[i] = a[j];
i = j;
j = (i-1)/2;
}
a[i] = item;
}
}
void adjust(int a[],int n)
{
int i,j,item;
j = 0;
item = a[j];
i = 2*j+1;
while(i<=n-1)
{
if(i+1 <= n-1)
if(a[i] <a[i+1])
i++;
if(item<a[i])
{
a[j] = a[i];
j = i;
i = 2*j+1;
} else
break;
}
a[j] = item;
}

3. Sort a given set of elements using the Merge sort method and determine the time
required to sort the elements. Repeat the experiment to different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken
versus
n.
#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
int a[20],i,j,n;
float v;
clock_t start,end;
clrscr();
start=clock();
printf("\nEnter the size of the array:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
end=clock();
v=(end-start)/CLOCKS_PER_SEC;
printf("\nSorted array is:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\nThe running time is:%2.4f",v);
getch();
}
int mergesort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
simplemerge(a,low,mid,high);
}
return 0;
}
int simplemerge(int a[],int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int c[20];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
c[k]=a[i];
i=i+1;
k=k+1;
}
else
{
c[k]=a[j];
j=j+1;
k=k+1;
}
}
while(i<=mid)
{
c[k++]=a[i++];
}

while(j<=high)
{
c[k++]=a[j++];
}
for(i=low;i<=high;i++)
{
a[i]=c[i];
}
return 0;
}

4. Sort a given set of elements using the Quick sort method and determine the time
required to sort the elements. Repeat the experiment to different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken
versus
n.
#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
int a[100],low,high,n,i,j;
float p;
clock_t start,end;
clrscr();
start=clock();
printf("\n How many elements:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
low=0;
high=n-1;
quicksort(a,low,high);
end=clock();
p=(end-start)/CLOCKS_PER_SEC;
printf("\n Sorted elemetns are:");
for(i=0;i<n;i++)
{
printf("%d \t",a[i]);
}
printf("\n");
printf("\n The running time is:%2.4f",p);
getch();
}
quicksort(int a[], int low, int high)
{
int keypos;
if(low>high)
return(0);
keypos=partition(a,low,high);
quicksort(a,low,keypos-1);
quicksort(a,keypos+1,high);
}
partition(int a[], int low, int high)
{
int i,j,pivot,temp,flag=1;
pivot=a[low];
i=low+1;
j=high;
flag=1;
while(flag==1)
{
while((a[i]<pivot)&&(i<j))
i=i+1;
while(a[j]>pivot)
j=j-1;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
flag=0;
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return(j);
}

5. Find Minimum cost spanning tree of a given undirected graph using Prim�s
algorithm.
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
clrscr();
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=99;
}
visited[1]=1;
printf("\n");
printf("Adjacency Matrix\n");
for(i=1;i<=n;i++)
{

printf("\n");
for(j=1;j<=n;j++)
{
printf("%d\t",cost[i][j]);
}
}
printf("\n");
while(ne<n)
{
for(i=1,min=99;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("Edge %d:(%d %d) cost:%d\n",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=99;
}
printf("\n Minimun cost is:%d",mincost);
getch();
}
//////////////////////////////////////PARDHU
Binary
#include

int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d",&n);

printf("Enter %d integers\n", n);


for (c = 0; c < n; c++)
scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first if (array[middle] < search)


first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
----------------------------------------------------------
Linear
#include

int main()
{
int array[100], search, c, n;

printf("Enter the number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

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


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}
--------------------------------
Linear multiple
#include

int main()
{
int array[100], search, c, n, count = 0;

printf("Enter the number of elements in array\n");


scanf("%d", &n);

printf("Enter %d numbers\n", n);

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


scanf("%d", &array[c]);

printf("Enter the number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++) {


if (array[c] == search) {
printf("%d is present at location %d.\n", search, c+1);
count++;
}
}
if (count == 0)
printf("%d isn't present in the array.\n", search);
else
printf("%d is present %d times in the array.\n", search, count);

return 0;
}
------------------------------------------
Bubble sort
#include

int main()
{
int array[100], n, c, d, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


scanf("%d", &array[c]);

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


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

printf("Sorted list in ascending order:\n");

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


printf("%d\n", array[c]);

return 0;
}
-----------------------------------------
Selection sort:
#include

int main()
{
int array[100], n, c, d, position, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


scanf("%d", &array[c]);

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


{
position = c;

for ( d = c + 1 ; d < n ; d++ )


{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}

printf("Sorted list in ascending order:\n");

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


printf("%d\n", array[c]);

return 0;
}
--------------------------------
Insertion sort:
#include

int main()
{
int n, array[1000], c, d, t;

printf("Enter number of elements\n");


scanf("%d", &n);
printf("Enter %d integers\n", n);

for (c = 0; c < n; c++) {


scanf("%d", &array[c]);
}

for (c = 1 ; cd = c;

while ( d > 0 && array[d-1] > array[d]) {


t = array[d];
array[d] = array[d-1];
array[d-1] = t;

d--;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c printf("%d\n", array[c]);


}

return 0;
}
-----------------------------------------------------------------------------------
-------------------------------------------
c++++++++++++++++++++++++
-----------------------------------------------------------------------------------
------------------------------------------
Binary :
#include

using namespace std;

int main()
{
int search(int [],int,int);
int n,i,a[100],e,res;
cout>n;
cout<

for(i=0;i<n;++i)
{
cin>>a[i];
}

cout>e;

res=search(a,n,e);

if(res!=-1)
cout<else
cout<

return 0;
}

int search(int a[],int n,int e)


{
int f,l,m;
f=0;
l=n-1;

while(f<=l)
{
m=(f+l)/2;
if(e==a[m])
return(m);
else
if(e>a[m])
f=m+1;
else
l=m-1;
}

return -1;
}
-----------------------------------------------------------------------------------
---------------------------------------
Linear:
#include

using namespace std;

int main()
{
int a[20],n,x,i,flag=0;
cout>n;
cout<

for(i=0;i<n;++i)
cin>>a[i];

cout>x;

for(i=0;i<n;++i)
{
if(a[i]==x)
{
flag=1;
break;
}
}

if(flag)
cout<else
cout<

return 0;
}
-----------------------------------------------------------------------------------
----------------------------------------------------
Insertion sort:
#include

using namespace std;


int main()
{
int i,j,n,temp,a[30];
cout>n;
cout<

for(i=0;i<n;i++)
{
cin>>a[i];
}

for(i=1;i<=n-1;i++)
{
temp=a[i];
j=i-1;

while((temp=0))
{
a[j+1]=a[j]; //moves element forward
j=j-1;
}

a[j+1]=temp; //insert element in proper place


}

cout<for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}

return 0;
}
-----------------------------------------------------------------------------------
-----------------------------------------

Bubble sort:
#include

using namespace std;

int main()
{
int a[50],n,i,j,temp;
cout>n;
cout<

for(i=0;i<n;++i)
cin>>a[i];

for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
cout<for(i=0;i<n;++i)
cout<<" "<<a[i];

return 0;
}
-----------------------------------------------------------------------------------
---------------------------------------------

Selection sort:
#include

using namespace std;

int main()
{
int i,j,n,loc,temp,min,a[30];
cout>n;
cout<

for(i=0;i<n;i++)
{
cin>>a[i];
}

for(i=0;i<n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
min=a[j];
loc=j;
}
}

temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}

cout<for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}

return 0;
}

////////////////////////////////////////////////////////////////////////pyramid

import java.util.Scanner;

/**
*
* @author Administrator
*/
public class Pyramind {
public static void main(String[]args){

Scanner sc = new Scanner(System.in);


System.out.println("Enter the n");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter numbers");
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
int b[]=new int[n];
int ctr=0;
for(int j=0;j<=i+1 & i+1<n;j++){
b[ctr]=a[j];
ctr++;

}
int sum=0;

for(int k=0;k<ctr;k++){
sum+=b[k];
}
for(int k=0;k<ctr-1;k++){
System.out.print(k+1+"+");

}
if(ctr>0){System.out.println(ctr+"="+sum);}

}
}
///////////////////////////////////////////////////////////////ANAGRAM

import java.util.Random;
import java.util.Scanner;

public class Anagram {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string\n");
String input=sc.nextLine();
String output="";
for(int i=0;i<input.length();i++){
int pos;
Random Random = new Random();
pos = Random.nextInt(input.length());
System.out.println(pos);
output+=input.charAt(pos);
}
// TODO code application logic here
System.out.println("Anagram= "+output );
}

}
////////////////////////////////////////////////////////////////////////NEAREST
PALINDROME

import java.util.Scanner;

/**
*
* @author Administrator
*/
public class NearestPalindrome {
public static int palin(int num){
int dup=num;

int i=0;
int rev=0;
while(num>0){
int dig=num%10;
rev=rev*10+dig;
num/=10;
}

if (dup==rev){
return 1;
}
else{
return 0;
}
}
public static void main(String[]args){

Scanner sc = new Scanner(System.in);


System.out.println("Enter the number");
int input=sc.nextInt();
int low=0;
int high=0;
int l[]=new int[10000];
int h[]=new int[10000];
int ctr1=0,ctr2=0;
int x=palin(input);
//if (x==1){
// System.out.println("Number itself a palindrome");

//}

for(int i=1;i<input;i++){
int ch=palin(i);
if(ch==1){
l[ctr1]=i;
ctr1++;
}
}
for(int i=input+1;i<10000;i++){
int ch=palin(i);
if(ch==1){
h[ctr2]=i;
ctr2++;
}
}

int ls=l[ctr1-1];
int hs=h[0];

int sub1=input-ls;
int sub2=hs-input;
// System.out.println(ls+","+hs);
//System.out.println(sub1+","+sub2);
if(sub1>sub2){
System.out.println(hs);
}
else if(sub1<sub2){
System.out.println(ls);
}
else if(sub1==sub2){
System.out.println(ls+" --"+hs);
}

}
}

You might also like