Tuesday, December 12, 2017

Algorithm + Insertion Sort + Selection Sort + BubbleSort + MergeSort + Quick Sort

Best programming questions.


http://www.java2novice.com/java-interview-programs/swap-two-numbers/


------------------------------------------------------------------------------------------

Find largest and smallest number in an array in java


package com.Algo;

public class AlgoTest {

public static void main(String[] args) {

int[] arr = { 3, 5, 7, 1, 9 };
int temp = 0;

int max = arr[0];
int min = arr[0];

for(int i=0; i<arr.length; i++)
{
if(arr[i]>max){
max = arr[i];
}
if(arr[i]<min){
min = arr[i];
}
}
System.out.println(max);
System.out.println(min);
}

}


Output : 9
              1
-----------------------------------------------------------------------------------------------------

Java program to find largest number in an array


    This example shows you how to find largest or maximum number in an array
    Step 1:
            Initialize array value
    Step 2:  (int max = a[0];)
            Initialize max value as array's first value
    Step 3: (for int i = 1; i < a.length; i++ )
            Iterate array using a for loop (exclude arrays first position 0, since it was assumed as max value)
    Step 4: if(a[i] > max)
            Use if condition to compare array current value with max value, if current array value is greater than max then assign array current value as max (max = a[i];).
    Step 5: 
            Continue the loop and resign the max value if array current value is greater than max

  1. class LargestNumber
  2. {
  3. public static void main(String args[])
  4. {
  5. int[] a = new int[] { 20, 30, 50, 4, 71, 100};
  6. int max = a[0];
  7. for(int i = 1; i < a.length;i++)
  8. {
  9. if(a[i] > max)
  10. {
  11. max = a[i];
  12. }
  13. }
  14. System.out.println("The Given Array Element is:");
  15. for(int i = 0; i < a.length;i++)
  16. {
  17. System.out.println(a[i]);
  18. }
  19. System.out.println("From The Array Element Largest Number is:" + max);
  20. }
  21. }
-----------------------------------------------------------------------------------------------------

Java program to find largest and second largest in an array


package com.Algo;

public class AlgoTestSecondLargest {

public static void main(String[] args) {

int arr[] = { 5, 34, 78, 2, 45, 1, 99, 23,99 };
int maxOne = 0;
int maxTwo = 0;
for (int i = 0; i < arr.length; i++) {

if (maxOne < arr[i]) {

maxTwo = maxOne;
maxOne = arr[i];
} else if (maxTwo < arr[i] && arr[i]!= maxOne) {

maxTwo = arr[i];
}
}
System.out.println("Largest Number: " + maxOne);
System.out.println("Second Largest Number: " + maxTwo);
}

}



Output :                    Largest Number: 99
                                 Second Largest Number: 78
----------------------------------------------------------------------------------------------------------

Java program to find second largest number in an array


  1. package com.candidjava;
  2. public class SecondLargest {
  3. public static void main(String[] args) {
  4. int arr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
  5. int largest = arr[0];
  6. int secondLargest = arr[0];
  7. System.out.println("The given array is:" );
  8. for (int i = 0; i < arr.length; i++) {
  9. System.out.print(arr[i]+"\t");
  10. }
  11. for (int i = 0; i < arr.length; i++) {
  12. if (arr[i] > largest) {
  13. secondLargest = largest;
  14. largest = arr[i];
  15. } else if (arr[i] > secondLargest) {
  16. secondLargest = arr[i];
  17. }
  18. }
  19. System.out.println("\nSecond largest number is:" + secondLargest);
  20. }
  21. }

    Output :

    The given array is: 14 46 47 86 92 52 48 36 66 85 Second largest number is:86 ------------------------------------------------------------------------

    Java program to find second largest number in an array

    package com.Algo; public class PraAlgoSecondHighestNum { public static void main(String[] args) { int[] arr = {122, 3, 4, 5, 1, 45,122 }; int maxLargest = 0; int maxSecondLargest = 0; for(int i =0; i<arr.length; i++){ if(maxLargest < arr[i]){ maxSecondLargest = maxLargest; maxLargest = arr[i]; } else if((maxSecondLargest<arr[i] && arr[i]!=(maxLargest))){ maxSecondLargest = arr[i]; } } System.out.println(maxLargest); System.out.println(maxSecondLargest); } }
Output : Largest Number: 99
              Second Largest Number: 78
-----------------------------------------------------------------------------------------------------------------

Find the smallest number in an array in java


package com.Algo;

public class SmallestNumberArray {

public static void main(String[] args) {

int[] a = {-5, -4, 0, 2, 10, 30, -3};
int smallest = 0;
    int secondSmallest = 0;
    for (int i = 0; i < a.length; i++) 
    {
     if(a[i]==smallest)
        {
          secondSmallest=smallest;
        } 
     else if (a[i] < smallest) 
        {
            secondSmallest = smallest;
            smallest = a[i];
        } 
    
    }
    System.out.println(smallest);
}

}


Output : 

Smallest number in Array : -5
------------------------------------------------------------------------------------------------------

Find the second smallest number in an array in java



package com.Algo;

public class SecondSmallestNumberArray {

public static void main(String[] args) {
int[] a = {-5, -4, 0, 2, 10, 30, -3};
int smallest = 0;
    int secondSmallest = 0;
    for (int i = 0; i < a.length; i++)
    {
     if(a[i]==smallest)
        {
          secondSmallest=smallest;
        }
     else if (a[i] < smallest)
        {
            secondSmallest = smallest;
            smallest = a[i];
        }
     else if (a[i] < secondSmallest)
        {
            secondSmallest = a[i];
        }
    
    }
    System.out.println("Second Smallest number in Array : "+ secondSmallest);
}

}

Output :

Second Smallest number in Array : -4
--------------------------------------------------------------------------------------------------------------

Duplicate elements in Array 

//Need to improve code for more boundaries result.//

package com.Algo.DuplicateElements.Array;

public class DuplicateElementsInArray {

public static void main(String[] args) {

// int arr[]= {1,3,3,5,5,6,7,10,5,10,6};
int arr[] = { 1, 1, 3, 5, 5, 1,3 };
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[i] == arr[j]) && (i!=j)) {
System.out.println("Duplicate Elements :" + arr[i]);

}
}
}

}


}


OUTPUT : Duplicate Elements :1
                  Duplicate Elements :1
                  Duplicate Elements :1
                  Duplicate Elements :3


                  Duplicate Elements :5

-----------------------------------------------------------------------------------------------------------------

Write a java program to find common elements between two arrays?

OR

Write a java program to find intersection of two arrays?


------------------------------------------------------------------------------------------------------------------

How To Find Duplicate Elements In An Array In Java?

There are many methods through which you can find the duplicate elements in the given array. In this post, I have discussed two of them. One is using Brute Force Method and another one is using HashSet.
1) Using Brute Force Method :
In this method, we compare each element of an array with other elements. If any two elements are found equal, we declare them as duplicates. The performance of this method is very low if an array contains lots of elements. Therefore, this method is not recommended in real time. It gives time complexity of O(n^2).
2) Using HashSet :
This method is better than the Brute Force method. It gives O(n) performance. You know that HashSet holds only unique elements. It never allows duplicate elements. We use this property of HashSet to find duplicates in an array. What we do is we try to add each element of an array into HashSet using add() method. This method adds only unique elements into HashSet. If you try to add duplicate element, it will return false.

Java Program To Find Duplicate Elements In An Array Using Brute Force Method :

public class DuplicatesInArray 
{   
 public static void main(String[] args) 
 {
  String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};

  for (int i = 0; i < strArray.length-1; i++)
  {
   for (int j = i+1; j < strArray.length; j++)
   {
    if( (strArray[i].equals(strArray[j])) && (i != j) )
    {
     System.out.println("Duplicate Element is : "+strArray[j]);
    }
   }
  }
 } 
}

Java Program To Find Duplicate Elements In An Array Using Brute Force Method :

public class DuplicatesInArray 
{   
 public static void main(String[] args) 
 {
  String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};

  for (int i = 0; i < strArray.length-1; i++)
  {
   for (int j = i+1; j < strArray.length; j++)
   {
    if( (strArray[i].equals(strArray[j])) && (i != j) )
    {
     System.out.println("Duplicate Element is : "+strArray[j]);
    }
   }
  }
 } 
}
OutPut :Duplicate Element is : def
Duplicate Element is : xyz

Java Program To Find Duplicate Elements In An Array Using HashSet :

import java.util.HashSet;

public class DuplicatesInArray 
{   
 public static void main(String[] args) 
 {
  String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};

  HashSet<String> set = new HashSet<String>();

  for (String arrayElement : strArray)
  {
   if(!set.add(arrayElement))
   {
    System.out.println("Duplicate Element is : "+arrayElement);
   }
  }
 } 
}
Output :
Duplicate Element is : xyz Duplicate Element is : def
-----------------------------------------------------------------------------
Reverse Array with int

public class JBC {

 public static void main(String[] args) {
   
  int[] arr = {1,2,3,4};
  
  int temp = 0;
  int len = arr.length;
  System.out.println("Ali");
  for(int i=0;i<len;i++){
   System.out.print(arr[i]+ " ");
  }
  
  for(int j=0;j<len/2;j++){
    
   temp = arr[j];
   arr[j] = arr[len-1-j];
   arr[len-1-j] = temp;
  }
  System.out.println();
  for(int i=0;i<len;i++){
   
   System.out.print(arr[i]+ " ");
  }
  
 }

}
OUTPUT : 

Ali
1 2 3 4 
4 3 2 1
----------------------------------------------------------------------------------------------
Reverse Array with String

public class ReverseArrStr
{

 public static void main(String[] args)
 {
  String[] arr = {"ABC","DEF","GHI","JKL","MNO"};
  int len = arr.length;
  String temp="";
  for(int i=0;i<arr.length;i++){
   System.out.print(arr[i]+" ");
  }
  
  for(int j=0;j<len/2;j++){
   temp = arr[j];
   arr[j] = arr[len-j-1];
   arr[len-j-1] = temp;
  }
  System.out.println();
  for(int i=0;i<arr.length;i++){
   System.out.print(arr[i]+" ");
  }
  
 }

}
OUTPUT:

ABC DEF GHI JKL MNO 

MNO JKL GHI DEF ABC
-----------------------------------------------------------------------------------------------------------------

Insertion Sort




package com.Algorithm.InsertionSort;

public class InsertionSort {

public static void main(String[] args) {

int arr[] = { 21, 4, 7, 29, 6 };
int j , temp,key;
int k=0;
for( k=0; k<arr.length;k++){
System.out.println(arr[k]+" ");
}
for(int i =0; i<arr.length; i++){
key = arr[i];
j = i-1;
while(j>=0 && key<arr[j]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
j--;
}
}
System.out.println("--------------------------------------");
for( k=0; k<arr.length;k++){
System.out.print(arr[k]+" ");
}

}

}

OUTPUT:-

21 
29 
--------------------------------------
4 6 7 21 29 





----------------------------------------------------------------------------------------------------------

Selection Sort 




package com.Algorithm.InsertionSort;

public class SelectionSort_2 {

public static void main(String[] args) {

int arr[] = { 21, 34, 54, 3, 67, 12 };
int j, minValue, minIndex, temp = 0;

for (int k = 0; k < arr.length; k++) {

System.out.print(arr[k] + " ");
}

for (int i = 0; i < arr.length; i++) {

minValue = arr[i];
minIndex = i;

for (j = i; j < arr.length; j++) {

if (arr[j]<minValue  ) {
minValue = arr[j];
minIndex = j;
}

}
if (minValue < arr[i]) {

temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}

}

System.out.println();
for (int k = 0; k < arr.length; k++) {

System.out.print(arr[k] + " ");
}

}

}


OUTPUT:-

21 34 54 3 67 12 
3 12 21 34 54 67 

----------------------------------------------------------------------------------------------------------

Bubble Sort

package com.Algorithm.BubbleSort;

public class BubbleSort_2 {

public static void main(String[] args) {

int arr[] = {21,43,56,65,12,3,4,7,1};
int j , temp=0;
for(int k =0; k<arr.length; k++){
System.out.print(arr[k] + " ");
}
for(int i=0; i<arr.length; i++){
for(j=0; j<arr.length-1-i; j++ ){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println();
for(int k =0; k<arr.length; k++){
System.out.print(arr[k] + " ");
}
}

}

OUTPUT:-

21 43 56 65 12 3 4 7 1 
1 3 4 7 12 21 43 56 65 




----------------------------------------------------------------------------------------

Merge Sort


-------------------------------------------------------------------------------------------------

Quick Sort





package com.Algorithm.QuickSort;

public class QuickSortAlgorithm_3 {

private static void quickSort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}

private static int partition(int arr[], int left, int right) {

int pivot = arr[(left + right) / 2];
while (left <= right) {

while (arr[left] < pivot)
left++;
while (pivot < arr[right])
right--;

if (left <= right) {

int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;

left++;
right--;
}
}

return left;
}

public static void main(String[] args) {

int arr[] = { 23, 89, 1, 9, 34, 2, 12, 33, 45, 65, 111 };

quickSort(arr, 0, arr.length - 1);

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

}

OUTPUT:-

1 2 9 12 23 33 34 45 65 89 111 
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment