1. Bubble Sort
package sort;
import java.util.Random;
/*To avoid running inner loop even though array is sorted
* We can pass swapped flag inside if statement
* Initialize flag to false as not element has swapped before start
swapping
* every time element get swapped set swapped flag to true
* after one iteration not single element swapped ie flag is
false
* means array is swapped already no need to make another
iteration
* get out of the loop
* this algorithm wont need (n^2) in best case
* in best case it perform result in even O(N) time
*/
public class BubbleSort {
public static void bubbleSort(int ar[]){
for(int
i=0;i<ar.length;i++){
boolean
swapped=false; //for each iteration set flag =false
for(int
j=1;j<ar.length;j++){
if(ar[j-1]>ar[j]){
int temp=ar[j-1];
ar[j-1]=ar[j];
ar[j]=temp;
swapped=true; //if swapped
flag =true
}
}
if(!swapped)
//if not element swapped at all
break; //array is sorted get out of loop
}
}
public static int[] getRandomNumberArray(int arraySize
,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
public static void main(String[] args) {
System.out.println("ArraySize\t
bubbleSort sort time taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
long startTime =
System.nanoTime();
bubbleSort(ar);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.println(" in NanoSec for bubbleSort sort
"+timeElapsed);
}
}
output
NanoSec for bubbleSort sort 15305910565
2. Merge Sort
package sort;
/*worst case of merge sort is NlogN
* Merge sort
* {20, 13, 4, 34, 5, 15, 90, 100, 75, 102}
* / \
* {20, 13, 4, 34, 5} {15, 90, 100, 75, 102}
* / \ / \
* {20, 13, 4}{34, 5} {15, 90, 100,} {75, 102}
* / \ / \ / \ / \
*{20, 13} {4} {34} {5} {15, 90} {100} {75} {102}
* / \ / \
*{20} {13} {15} {90}
*
*Height of above tree is Log(N)
*to merge the array two temp array it will take o(N) in worst
case
*so total time complexity it O(Nlog(N))
*
*/
import java.util.Random;
public class MergeSort {
int ar[];
MergeSort(int ar[]){
this.ar=ar;
}
public static void mergeSort(int ar[],int l,int
r){
if(l<r){
int mid=(l+r)/2;
//take mid index
mergeSort(ar,l,mid); //call mergesort on first half
mergeSort(ar,mid+1,r); // and second half
marge(ar,l,r,mid); //no merge the two in sorted manner
}
}
public static void marge(int ar[],int l,int r,int
mid){
int t1[]=new int[mid-l+1]; //make
temp array of first hlaf size and
int t2[]=new int[r-mid]; //second
half size
int k=0; //index to 0
for(int i=l;i<=mid;i++){ //copy
fist half elements to first temp array
t1[k++]=ar[i];
}
k=0;
for(int i=mid+1;i<=r;i++){
//copy second half array to sec temp array
t2[k++]=ar[i];
}
k=0;
int k1=0; //from those two temp
array copy elements in sorted array in original array
while(k<t1.length &&
k1<t2.length){
if(t1[k]<=t2[k1]){ //if t1's element is less first copy it
ar[l++]=t1[k++];
}
else{
ar[l++]=t2[k1++]; //else t2's
}
}
while(k<t1.length){ //copy the
remaining elements
ar[l++]=t1[k++];
}
while(k1<t2.length){
ar[l++]=t2[k1++];
}
}
public static int[] getRandomNumberArray(int arraySize
,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
//driver program to test
public static void main(String[] args) {
System.out.println("ArraySize\tMerge sort time taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
long startTime =
System.nanoTime();
mergeSort(ar, 0,
ar.length-1);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.print(ar.length+" "+ timeElapsed+" in NanoSec for Merge
sort ");
}
}
output
ArraySize Merge sort time taken
100000 29742747 in NanoSec for Merge sort
3. Heap Sort
package sort;
import java.util.Random;
/*
* It is proved that time complexity for making heap is O(n)
* Heapify takes place in log(n)
*/
public class HeapSort {
static int heap[];
static int heapSize=0;
static int OrheapSize=0;
public static int[] makeHeapMin(int ar[],int k){
heap=new int[ar.length];
for(int
i=0;i<ar.length;i++){
heap[heapSize]=ar[i]; //first size will be
zero
OrheapSize=heapSize; //store current size
//find correct position to store element
//until size not equal to zero and parent
element is greater then current, ,make current ele as parant
while(heapSize!=0 &&
heap[getParant(heapSize)]>heap[heapSize]){
int
temp=heap[getParant(heapSize)];
heap[getParant(heapSize)]=heap[heapSize];
heap[heapSize]=temp;
heapSize=getParant(heapSize);
}
heapSize=OrheapSize;
heapSize++;
//increase heap size by
}
return heap;
}
public static int getRight(int i){
return 2*i+2;
}
public static int getLeft(int i){
return 2*i+1;
}
public static int getParant(int i){
return (i-1)/2;
}
public static void heapify(int i,int heap[]){
int l=getLeft(i); //find the left
index of i
int r=getRight(i); //right index of
i
int min=i; //make ith element as
minimum stroe its index
if(l<heapSize &&
heap[l]<heap[min]){ //check where left element is min or
not
min=l; // if yes
mark l as min
}
if(r<heapSize &&
heap[r]<heap[min]){ //same for right
min=r;
}
if(min!=i){ //ith element was not
min swap it with actual min
int
temp=heap[i];
heap[i]=heap[min];
heap[min]=temp;
heapify(min,heap); //do recursively for next min
}
}
public static int extractMin(int heap[]){
int min=-1;
if(heapSize<0)
return
min;
if(heapSize==1){
heapSize--;
return
heap[0];
}
else{
min=heap[0];
heap[0]=heap[heapSize-1];
heapSize--;
heapify(0,heap);
}
return min;
}
public static void printHeap(int ar[]){
for(int
i=0;i<ar.length;i++){
System.out.print(ar[i]+" ");
}
System.out.println(" ");
}
public static int[] getRandomNumberArray(int arraySize
,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
public static void HeapSort(int ar[]){
for(int
i=0;i<ar.length;i++){
extractMin(ar);
}
}
public static void main(String[] args) {
System.out.println("ArraySize\tSelection sort time
taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
ar=makeHeapMin(ar,ar.length);
long startTime =
System.nanoTime();
HeapSort(ar);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.print(ar.length+" "+ timeElapsed+" in NanoSec for Heap
sort ");
}
}
output
ArraySize Selection sort time taken
100000 10392517 in NanoSec for Heapsort
Selection Sort
package sort;
import java.util.Random;
public class Selection {
public static void main(String[] args) {
System.out.println("ArraySize\tSelection sort time taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
long startTime =
System.nanoTime();
doSelectionSort(ar);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.print(ar.length+" "+ timeElapsed+" in NanoSec for
Selection sort ");
}
public static int[] getRandomNumberArray(int
arraySize ,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
public static int[] doSelectionSort(int[]
placer){
for (int index=0;index<placer.length;index++)
{
int smallerNumber = placer[index];
//make current element as smallest
int smallerIn=-1; //initialize
smallest index as -1
int i=index; //define i out so that
it remain accessible out side of loop
for(;i<placer.length;i++){ //find smallest element
in ar[i.....n]
if(smallerNumber>placer[i]){
smallerNumber=placer[i];
smallerIn=i;
//remember index of smallest
}
}
if(smallerIn!=-1){ //if smallest found
int temp=placer[index]; //swap it
placer[index]=smallerNumber;
placer[smallerIn] = temp;
}
}
return placer;
}
}
output
ArraySize Selection sort time taken
100000 1645443135 in NanoSec for Selection sort
Binary Search
package search;
/*
* This is not true .
* when we doing liner search and array is sorted, we want to search
max element it will take n-1 comparision
* we want to search min element it will take 1 comparison
* if array is not sorted it might take either 0 ..to .. n
comparison
* that why we say in worst case time complexity of liner search
O(N)
* but in Binary search max no of comparison is log(n) in worst
case
* in best case one comparison
*
*/
import java.util.Random;
public class BinarySearch {
static int c=0; //variable to count comparison
public static int binarySearch(int ar[],int l,int
r,int k){
if(l>r) //if left greater then r
element not found
return -1;
int mid=(l+r)/2; //find mid
index
if(ar[mid]==k){ //if mid is desired
no return index
++c; //increase
count
return
mid;
}
if(k<ar[mid]){ //if k less then
mid element go to left array
++c; //increase
count
return
binarySearch(ar,l,mid-1,k);
}
else{
++c; //if k
greater then mid element go to right array
return
binarySearch(ar,mid+1,r,k);
}
}
public static int[] getRandomNumberArray(int arraySize
,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
//driver program to test
public static void main(String[] args) {
System.out.println("ArraySize\tBinary Search time taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
long startTime =
System.nanoTime();
binarySearch(ar,0, ar.length-1, 7);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.print(ar.length+" "+ timeElapsed+" in NanoSec for Binary
Search ");
}
}
output
ArraySize Binary Search time taken
100000 9062 in NanoSec for Binary Search
Liner Search
package search;
import java.util.Random;
public class LinerSearch {
static int c=0; //variable to count comparison
public static int linerSearch(int ar[],int
x){
for(int
i=0;i<ar.length;i++){
if(ar[i]==x){
//if element is x
c++; //increase count
return i; //return index
}
c++; //else
increase count as element still being compared
}
return -1;
}
public static int[] getRandomNumberArray(int arraySize
,int numberOfDigits ){
int ar[]=new int[arraySize];
Random rnd = new Random();
int n = numberOfDigits +
rnd.nextInt(numberOfDigits);
for(int
i=0;i<ar.length;i++){
ar[i]=numberOfDigits + rnd.nextInt(numberOfDigits);
}
return ar;
}
//driver program to test
public static void main(String[] args) {
System.out.println("ArraySize\tLiner Search time taken");
int size=100000;
int
ar[]=getRandomNumberArray(size,3);
long startTime =
System.nanoTime();
linerSearch(ar,
7);
long endTime =
System.nanoTime();
long timeElapsed
= endTime - startTime;
System.out.print(ar.length+" "+ timeElapsed+" in NanoSec for Liner
Search ");
}
}
output
ArraySize Liner Search time taken
100000 1552610 in NanoSec for Liner Search
Step 1: Select any four sorting algorithm and two searching algorithms Step 2: Understand the logic...
Using Arrays with Sorting and Searching Algorithms 1) This program has six required outputs and involves searching and sorting an array of integers. Write a java application that initializes an array with the following numbers, in this order: 23, 17, 5, 90, 12, 44, 38, 84, 77, 3, 66, 55, 1, 19, 37, 88, 8, 97, 25, 50, 75, 61, and 49. Then display the unsorted values. This is required output #1 of 6 for this program. 2) Using a...
How to measure the average performance of sorting algorithms with different sizes and numbers(with arrayList<Integer>) and compare with a graph? I have these methods: //This one receives one size(n) parameter public static ArrayList<Integer> RandomArray(int n){ ArrayList<Integer> randomArray = new ArrayList<Integer>(n); Random rand = new Random(); //--- random number rand.setSeed(System.currentTimeMillis()); for(int i = 0; i < n; i++ ) { //loop for creating...
Comparison of Sorting Algorithms You are required to implement all the sorting algorithms (Bubble, Selection, Insertion, Quick, Merge). Take help from lecture slides and welb . You will then create arrays of different sizes as instructed below, test each algorithm on each array and record the execution times of each individual algorithm on each array. . You will report these execution times in a table and then write a report explaining the execution times of the sorting algorithms according to...
I need the report like this (idea) *Sorting Algorithms: A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) which require input data to be in sorted lists; it is also often useful for canonical zing data and for producing human-readable output. More formally, the output must satisfy...
1. a. Using C++, represent the following graph using adjacency matrix, and implement depth first searching (DFS) by stack (define it with class) to traverse the graph. 6 7 2 4 b. If starting with node 2, when node 7 is printed, what numbers are in the stack (for DFS)? Please draw the stack step by step to show how the numbers are pushed into and popped out of it. 2. a. Given a set of integer numbers as int...
//Generic interface that describes various searching and sorting //algorithms. Note that the type parameter is unbounded. However, //for these algorithms to work correctly, the data objects must //be compared using the method compareTo and equals. //In other words, the classes implementing the list objects //must implement the interface Comparable. The type parameter T //is unbounded because we would like to use these algorithms to //work on an array of objects as well as on objects of the classes //UnorderedArrayList and...
Objective: in Java Write a program that implements 3 sorting algorithms and times them in real time. These algorithms will sort Cylinders by their volume. First, download the driver and include it in your project. Write a class Cylinder with the following properties baseRadius: a non-negative number that corresponds to the Cylinder’s base’s radius. height: a non-negative number that corresponds to the Cylinder’s height. Next, write a class Sorter with the following bubbleSort: This static method takes in an array...
Hi i will give you a thumbs up if you do this problem correctly. Sorting Analysis Code and Essay Due: 4/22/2019(Monday) Introduction And now for something completely different. Different sorting algorithms are better for different size data sets. Other sorting algorithms are better for data sets of a specific type – for instance, data that is already ordered. In this assignment you will implement four different sorting algorithms and collect statistics for each of those algorithms while sorting multiple different...
Step One This is the Measurable interface we saw in class; you will need to provide this class; this is it in its entirety (this is literally all you have to do for this step): public interface Measurable double getMeasure(); Step Two This is the Comparable interface that is a part of the standard Java library: public interface Comparable int compareTo (Object otherObject); Finish this class to represent a PiggyBank. A PiggyBank holds quarters, dimes, nickels, and pennies. You will...
In this project, you will work on the algorithm (discussed in Module 1) to determine the length of the longest sub sequence of consecutive integers in an array You will implement the algorithm using Hash tables. You are provided with sample code (in C++ and Java) representing the linked list-based implementation of Hash tables (as an array of Linked Lists). You could go through the code to understand the implementation of a Hash table and the functions that can be...