0% found this document useful (0 votes)
10 views16 pages

Java Sorting and Rearranging Algorithms

Uploaded by

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

Java Sorting and Rearranging Algorithms

Uploaded by

mairasworld202
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAM 2 : SORTING NUMBERS USING SELECTION SORT METHOD

import [Link].*;
class SelSort
{
int a[],n;
SelSort(int nn)=]
{
n=nn;
a=new int[n];
}
void input()
{
Scanner sc=new Scanner([Link]);
int i;
[Link]("enter "+ n +" numbers");
for(i=0;i<n;i++)
{
a[i]=[Link]();
}
}
void sort()
{
int i,j,t,small,pos;
for(i=0;i<n-1;i++)
{
small=a[i];
pos=i;
for(j=i+1;j<n;j++)
{
if(a[j]<small)
{
small=a[j];
pos=j;
}
}
t=a[i];
a[i]=a[pos];
a[pos]=t;
}
}
void display()
{
int i;
[Link]("sorted array");
for(i=0;i<n;i++)
[Link](a[i]);
}
public static void main()
{
Scanner sc=new Scanner([Link]);
int p;
[Link]("enter size of array");
p=[Link]();
SelSort ob=new SelSort(p);
[Link]();
[Link]();
[Link]();
}
}

PROGRAM 3
A class Rearrange has been defined to modify a word by
bringing all the vowels in the word at the beginning
followed by the consonants.
Example:
ORIGINAL becomes OIIARGNL
Some of the members of the class are given below:
Class name: Rearrange
Data Member/instance variable:
wrd: to store a word
newwrd: to store the rearranged word
Member functions/methods:
Rearrange(): default constructor
void readword(): to accept the word in UPPER case
void arrange(): rearranges the word by bringing the
vowels at the beginning followed by consonants
void display(): displays the original word along with the
rearranged word
Specify the class Rearrange, giving the details of the
constructor(), void readword(), void arrange() and void
display(). Define the main() function to create an object
and all the functions accordingly to enable the task.

import [Link].*;
class Rearrange
{
String wrd;
String newwrd;
Rearrange()
{
wrd="";
newwrd ="";
}
void readword()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the word in Uppercase:");
wrd = [Link]();
}
void arrange()
{
int l=[Link]();
char ch;
String vs ="";
String cs ="";
for(int i = 0; i < l; i++)
{
ch = [Link](i);
if(ch=='A'||ch=='E'||ch== 'I'||ch== 'O'||ch== 'U' )
vs=vs+ ch;
else
cs=cs+ ch;
}
newwrd = vs + cs;
}
void display()
{
[Link]("Original word:" + wrd);
[Link]("Rearranged word:" + newwrd);
}
public static void main()
{
Rearrange obj = new Rearrange();
[Link]();
[Link]();
[Link]();
}
}
import [Link].*;
class VowelWord
{
String str;
int freq;

VowelWord()
{
str="";
int i,c=0;
char ch; String wd="";
StringTokenizer st=new StringTokenizer(str," !?.");
c=[Link]();
for(i=0;i<c;i++)
{
wd=[Link]();
if([Link](0)=='A' || [Link](0)=='E' ||[Link](0)=='I' ||
[Link](0)=='O' ||[Link](0)=='U')

freq++;
}
}

void display()
{
[Link]("Frequency of words beginning with vowel=" +freq);
}
public static void main()
{
VowelWord ob=new VowelWord();
[Link]();
ob.freq_vowel();
[Link]();
}
}

1
{
if(n%i==0)
{
c++;
}
}
if (c==2)
return 1;
int r,rev=0;
while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
return rev;
}
int isadam (int n)
{
int sq=1 , sqr=1,p;
sq= n*n;
p= reverse(n);
sqr=p*p;
int a= reverse(sqr);
if (a==sq)
return 1;
else
return 0;
}
void main ()
{
int i , c=0,m,n;
Scanner sc=new Scanner([Link]);
[Link]("INPUT");
[Link]("m=");
m=[Link]();
[Link]("n=");
n=[Link]();
[Link]("OUTPUT");
if (m>0)
{
[Link]("the prime adam integers are");
for(i=m;i<=n;i++)
{
if(prime(i)==1 && isadam(i)==1)
{
[Link](i+"\t");
c++;
}
}
[Link]();
[Link]("Frequency of prime adam integer is "+c);
if(c==0)
[Link]("NIL");
}
else
[Link]("Invalid Input");
}
}
ALGORITHM
Step 1: Start
Step 2: Create a function to check if a number is prime or not.
Step 3: Create a function to store the reverse.
Step 4: Create a function to check if a number is an Adam number or not.
Step 5: Iterate through a range of numbers and check if each number is both
prime and Adam.
Step 6: If a number satisfies both conditions, print it.
Step 7: Create main function.
Step 8: stop.

A class Fibo has been designed to generate Fibonacci Series-


0,1,1,2,3,5,13……..
CLASS : Fibo
DATA MEMBERS:
start : int to store start value
end : int to store end value
MEMBER FUNCTIONS:
Fibo(): default constructor
void read(): to accept start and end
int fibo(int n): returns nth term of Fibonacci series using recursive technique
void display():displays Fibonacci series from start to end by invoking function
Fibo()
Define the main() function to create an object and all the functions accordingly
to enable the task.

import [Link].*;
class Fibo
{
int start,end;
Fibo()
{
start=0;
end=0;
}
void read()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter starting and end limit");
start=[Link]();
end=[Link]();
}
int fibo(int n)
{
if(n==1||n==0)
return n;
else
return(fibo(n-1)+fibo(n-2));
}
void display()
{
int i;
for(i=start;i<=end;i++)
{
[Link](fibo(i)+" ");
}
}
}

11 5 7
8 13 9 A class Trans is defined to find the transpose of a square matrix. A
1 6 20 transpose of a matrix is obtained by interchanging the elements of
rows and columns.
Example : If size of matrix is 3

ORIGINAL 11 8 1
TRANSPOSE 5 13 6
7 9 20

CLASS NAME : Trans


DATA MEMBERS:
arr[][]: to store numbers in array
m: to store array size
MEMBER METHODS:
Trans(int mm): to initialize m=mm
void fillarray(): to input numbers in array.
void transpose(): to create transpose of matrix.
void display(): display original matrix and transposed matrix by invoking
transpose()
Define the main() function to create an object and all the functions accordingly
to enable the task.

Common questions

Powered by AI

In Java classes like Rearrange and Fibo, constructors play a vital role by initializing objects. Constructors set initial values for the object's fields, ensuring they are in a valid state before use. In Rearrange, the constructor initializes 'wrd' and 'newwrd' strings, preparing the object for subsequent operations without uninitialized field errors. In Fibo, the constructor sets start and end to default small values. This promotes encapsulation and simplicity, allowing objects to be instantiated correctly without reliance on external initialization after creation .

The Java program finds prime adam integers, numbers that are both prime and Adam numbers. An Adam number is one where the square of the number remains the same when reversed and squared again. The process involves first checking if a number is prime, and then verifying its Adam property by squaring the number, reversing it, and comparing the results. The program iterates through a range, checking these conditions for each number. The significance lies in finding numbers that hold both properties, which is a topic of mathematical curiosity and challenges common number theory assumptions .

In Java, the main method serves as the entry point for program execution, from which other member functions can be called to perform specific tasks. In the Rearrange class, the main method creates an instance of Rearrange, and sequentially calls 'readword', 'arrange', and 'display' methods to input a word, rearrange it, and display the result. Similarly, in the Fibo class, the main method creates a Fibo object, calling 'read' to accept input limits, 'fibo' for Fibonacci computations, and 'display' to show results. This structured approach organizes program flow and facilitates testing .

Separating input validation in Java programs is crucial for ensuring the program's robustness and reliability. It acts as the first line of defense against invalid input that can lead to runtime exceptions or incorrect results. For instance, when reading integers or strings, validating input ensures that the processing logic receives expected data types and formats, thus minimizing errors and enhancing clarity. Such separation promotes maintainability by modularizing logic, allowing ease of updates or bug fixes without restructuring the primary computational logic .

The 'fibo' function calculates the nth term of the Fibonacci series using recursion by returning the sum of the two preceding numbers in the series. The base case for the recursion is when n is 0 or 1, where it simply returns n. Recursion facilitates the task by breaking down the problem into simpler subproblems. However, this approach is inefficient, with a time complexity of O(2^n), due to the repeated calculation of the same Fibonacci numbers, making it impractical for larger values of n without optimization techniques like memoization .

The provided Java program implements the Selection Sort method, which sorts an array by repeatedly finding the minimum element from the unsorted part and moving it to the beginning. The main operations involve nested loops where the outer loop runs from 0 to n-1, and the inner loop finds the smallest element in the unsorted part. Elements are then swapped. The time complexity of Selection Sort is O(n^2) in all best, average, and worst-case scenarios because it always involves two nested loops. There are no conditions that significantly alter the execution path in terms of elapsed time .

The algorithm in the Trans class computes the transpose of a matrix by interchanging the matrix's rows and columns. It iterates over the matrix with a nested loop: the outer loop going through each row, the inner loop through each column, swapping elements as needed. This results in a transposed matrix where each a[i][j] element becomes a[j][i]. The computational complexity is O(n^2) for a square matrix, as each element must be accessed and potentially swapped, making the complexity quadratic concerning the size of the matrix .

The Rearrange class reads a word in uppercase, and separates vowels and consonants into two strings. It first initializes two empty strings, 'vs' for vowels and 'cs' for consonants. It iterates over each character in the input word, checking if each character is a vowel. If it is, it's appended to 'vs', otherwise, to 'cs'. The rearranged word is then constructed by concatenating 'vs' and 'cs'. The operation is linear with respect to the length of the word, O(n), making it efficient for typical word lengths as it involves a single pass through the string .

When implementing matrix transposition, design considerations include ensuring that the data structure accommodates square matrices since transposition inherently assumes a matrix with dimensions m x n where m = n. Memory usage should be optimized by reusing the existing array for in-place modifications or creating a new array for the transposed matrix if necessary. Since transposition changes the matrix's memory layout, care must be taken to correctly adjust the access patterns. Additional considerations might include extending algorithms to handle non-square matrices and improving computational efficiency .

The method in the VowelWord class calculates the frequency of words starting with vowels by tokenizing the input string and checking each word's first character. The word count is incremented if the first character is a vowel. This method's efficiency mainly relies on the StringTokenizer's performance and the iteration over all words. Its time complexity is O(n), where n is the number of words. While efficient for typical string lengths, the readability and support for various delimiters could be improved by using modern Java string processing features like regular expressions .

You might also like