array – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 10 Mar 2024 17:00:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg array – Programmerbay https://programmerbay.com 32 32 C Program to Sort an array using Selection Sort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-selection-sort/ https://programmerbay.com/program-to-sort-an-array-using-selection-sort/#respond Sun, 03 Mar 2024 17:20:38 +0000 https://www.programmerbay.com/?p=2879 The program sorts uses Selection Sort technique to sort the given array. There are bunch of sorting mechanisms such as Bubble sort, Insertion sort and more to achieve this functionality. In this, we’ll be only focusing Selection Sort .

Selection Sort

Selection sort is a sorting technique wherein at each iteration, a minimum element is selected from an unsorted array and compared with all other remaining elements. if an element is found that is smaller than already assumed minimum element,  swapping would be performed.

It divides an array into two parts. One that is already sorted and another one which is still unsorted that need to be arranged.

From unsorted sublist, the algorithm finds the minimum element and adds on to sorted category. It ends when we get a single consolidated sorted sublist.

Pseudocode

FOR i=0 to Array.Length
minimum = i
FOR j=0 to Array.Length
if A[min]< A[j])
Swap A[min] with A[j]
End IF
END FOR
END FOR

C program to sort an array using Selection Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp,min;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<=size-1;i++)
{
min= i;
for(j=0;j<=size-1;j++)
{
if(arr[min]<arr[j]){
temp = arr[j];
arr[j] =arr[min];
arr[min] = temp;
}
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

Output:

Screenshot from 2024 03 10 22 22 03

 

How does Selection Sort work?

Screenshot from 2024 03 10 22 28 33

 

Lastly, it is an inefficient algorithm for the large dataset as it requires O(n2) comparisons in all cases worst, average and best case. It is simple and occasionally has an upper hand over other complicated algorithms.

]]>
https://programmerbay.com/program-to-sort-an-array-using-selection-sort/feed/ 0
Java program to Add Two Matrices Using Two Dimensional Array https://programmerbay.com/java-program-to-add-two-matrices/ https://programmerbay.com/java-program-to-add-two-matrices/#respond Thu, 11 Aug 2022 10:07:13 +0000 https://www.programmerbay.com/?p=2343 The program adds two matrices with the help of two-dimensional arrays. It is achieved by frequently adding an element of first array with an element at the same index of second array and the sum stores to new array. Given two matrices below :

Java program to add two matrices

Java program to Add Two Matrices Using Two Dimensional Array

It uses the Scanner Class to accept input from the user in both the matrices and then using a nested loop, addition is performed on those matrices are performed.

Program:

public class AddTwoMatrices {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int row, col, i, j;
        System.out.println("Enter number of rows");
        row = ed.nextInt();
        System.out.println("Enter number of column");
        col = ed.nextInt();
        int[][] a = new int[row][col];
        int[][] b = new int[row][col];
        int[][] sum = new int[row][col];
        System.out.println("Enter first matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                a[i][j] = ed.nextInt();
            }
        }
        System.out.println("Enter Second matrix");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                b[i][j] = ed.nextInt();
            }
        }
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                sum[i][j] = b[i][j] + a[i][j];
            }
        }
        System.out.println("Sum of two matrices");
        for (i = 0; i < row; i++) {
            for (j = 0; j < col; j++) {
                System.out.print(sum[i][j]+" ");
            }
            System.out.print("\n");
        }
    }
}

Output:

Enter number of rows
2
Enter number of column
3
Enter first matrix
8
5
3
2
1
4
Enter Second matrix
5
3
2
1
5
6
7
Sum of two matrices
13 8 5 
3 6 10 

 

Explanation :

  1. It accepts the size of the matrix ( row and column ) and also the values of the matrix as input from the user for the
  2. By traversing, every element of first array added to the corresponding element of another array
  3. Lastly, Printing the array on the output screen.

]]>
https://programmerbay.com/java-program-to-add-two-matrices/feed/ 0
Java program to remove duplicate elements from an array https://programmerbay.com/java-program-to-remove-duplicate-elements-from-an-array/ https://programmerbay.com/java-program-to-remove-duplicate-elements-from-an-array/#respond Mon, 07 Dec 2020 08:00:54 +0000 https://www.programmerbay.com/?p=4162 Simple Java programs that remove duplicate elements from a given array.

This is a bit tricky problem. In this, we have to remove all the duplicate elements from the array. for example, {2,3,5,5,6,2},  as you can see there are some duplicates can be seen and the task is to remove these elements so that we can get an array of unique elements, that is {2,3,5,6}.

Given an array and we need to remove duplicate elements using Java program.

Input array elements:
1, 2, 3, 1, 2, 3, 4

Output:
1, 2, 3, 4

There are various ways to remove duplicate elements from array, here are few of them:

  • Directly removing duplicate elements from array
  • Eliminating duplicate elements by sorting the array first
  • Removing duplicate elements using LinkedHashSet
  • Getting unique elements using Streams ( Java 8 Feature )

1. Java program to remove duplicate elements from an array

Program:

public class Duplicate_int {

public static void main(String[] args) {
int index=0;
int[] arr = {10,20,20,50,50,45};
int size = arr.length;
int duplicate,flag=0,count;
int[] anti_dup= new int[size];
int i,j;
System.out.println("Before removing duplicate from the array:");
for(i=0;i<size;i++)
{
System.out.println(arr[i]);
}

for(i=0;i<size;i++)
{
count=0;
for(j=i+1;j<size;j++)
{
if(arr[i]==arr[j])
{
count=count+1;
break;
}

} 
if(count==0)
{
anti_dup[index]=arr[i];
index++;
}
}

for(i=0;i<index;i++)
{
arr[i]=anti_dup[i];
}
System.out.println("After removing duplicate from the array");
for(i=0;i<index;i++)
{
System.out.println(arr[i]);
}

}
}

Output:

Before removing duplicate from the array:
10
20
20
50
50
45
After removing duplicate from the array
10
20
50
45

2. Java program to remove duplicate elements from an array By Sorting it first

Program: 

import java.util.*;

public class RemoveDuplicate {
    public static void main(String[] args) {
        int[] arr = {6, 2, 3, 4, 43, 6, 7, 5, 6, 34, 4};
        int[] uniqueArr = new int[arr.length];
        int counter = 0;
        Arrays.sort(arr);
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] != arr[i + 1]) {
                uniqueArr[counter] = arr[i];
                counter++;
            }
        }
        uniqueArr[counter] = arr[arr.length - 1];
        System.out.println("Array with Unique Elements : ");
        for (int i = 0; i <= counter; i++) {
            System.out.println(uniqueArr[i]);
        }
    }
}

Output:

Array with Unique Elements : 
2
3
4
5
6
7
34
43

3. Remove Duplicate Elements using Streams

Program:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicateExample {

    public static void main(String[] args) {
        Integer[] numberArr = new Integer[] {10,30,30,10,15,13,34,15};

       List<Integer> uniqueList = Arrays.asList(numberArr).stream().distinct().collect(Collectors.toList());
        for (Integer singleElement:
            uniqueList ) {
            System.out.println(singleElement);
        }

    }

}

Output:

10
30
15
13
34

Explanation:

In above code, we first converted given array to list, then eliminated duplicated using distinct function and collected it in form of list. Lastly, we printed the list.

4. Removing duplicates using LinkedHashSet

Program:

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateExample {

    public static void main(String[] args) {
        Integer[] numberArr = new Integer[] {10,30,30,10,15,13,34,15};
       Set<Integer> uniqueSet = new LinkedHashSet<>(Arrays.asList(numberArr));
        for (Integer singleElement:
            uniqueSet ) {
            System.out.println(singleElement);
        }

    }

}

Output:

10
30
15
13
34

Explanation:

In above program, we used linkedHashSet in order to have unique elements and to maintain the order. We all know, a set doesn’t allow duplicates, therefore, using that property we’re able to remove the duplicates.

]]>
https://programmerbay.com/java-program-to-remove-duplicate-elements-from-an-array/feed/ 0
C Program to sort an array using Quicksort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-quicksort/ https://programmerbay.com/program-to-sort-an-array-using-quicksort/#respond Thu, 11 Jun 2020 12:05:22 +0000 https://www.programmerbay.com/?p=2894 Quicksort is based on Divide and Conquer paradigm. It works by partitioning the given input array into two subarrays and sorts them through recursive calls until they get sorted.

In this, a pivot element is used that acts as a base for partitioning the array, where element lesser than pivot element arranged at the left side and bigger ones at the right side.

It requires O(n log n) running time to sort the given array when it comes to the average case.

Therefore, it can be used to sort a large set of elements. However, in the worst case, the running time of this algorithm hops up to O(n2).

Pseudocode

Quicksort( Array,first,last)
IF first <last
partitionpoint = Partition(arr,first,last);
Quicksort(Array,first,partitionpoint-1)
Quicksort(Array,partitionpoint+1,last)

Partitioning

Partition(Array,first,last)
pivot = arr[last]
i=first-1
FOR j=first to last - 1
IF Array[j]<pivot
i=i+1
exchange Array[i] with Array[j]
END IF
END FOR
exchange Array[i] with Array[last]
return i+1

C program to sort an array using Quicksort in Ascending Order

#include<stdio.h>
#define size 5

void quicksort(int arr[],int first,int last)
{

if(first <last)
{
int partitionpoint;
partitionpoint = sort_me(arr,first,last);
quicksort(arr,first,partitionpoint-1);
quicksort(arr,partitionpoint+1,last);
}

}

int sort_me(int arr[],int first,int last)
{
int pivot = arr[last],j,temp,n;
int i=first-1;
for(j=first;j<last;j++)
{
if(arr[j]<pivot)
{
i++;
temp =arr[j];
arr[j]=arr[i];
arr[i]=temp;

}
}
temp =arr[i+1];
arr[i+1]=arr[last];
arr[last]=temp;

return i+1;
}

int main()
{
int arr[size],j,temp,n;
printf("Please enter elements: \n "); 
for(n=0;n<=size-1;n++)
{
scanf("%d",&arr[n]);
}

quicksort(arr,0,size-1);

printf(" \n Sorted Elements :");

for(n=0;n<=size-1;n++)
{
printf("\n %d ",arr[n]);
} 
return 0;

}

 

Output:

quicksort

]]>
https://programmerbay.com/program-to-sort-an-array-using-quicksort/feed/ 0
C program to sort an array using Bubble Sort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/ https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/#respond Wed, 10 Jun 2020 10:56:44 +0000 https://www.programmerbay.com/?p=2867 The program sorts an array in ascending order based on the given input. There are various sorting algorithms to achieve this functionality Such as Selection Sort, Insertion sort and more . In this, We’ll be using Bubble Sort algorithm.

Bubble sort is one of the simplest and most popular algorithms, but inefficient. It repeatedly compares each element with their adjacent elements and performs swapping if required.

Pseudocode

FOR i=0 to Array.Length
FOR j=Array.Length-1 to i
IF A[j]< A[j-1])
Swap A[j] and A[j-1]
END IF
END FOR
END FOR

C program to sort an array using Bubble Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 5
void main()
{
int arr[size],i,j,temp;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

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

}

}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();

}

 

Output:

bubble sort 1

How does Bubble Sort program work?

bubble sort working

It requires a constant amount O(1) of additional memory space and O(n2) comparisons in the worst case and average case to sort an array.

However, this sorting technique is too slow and impractical if we compare it with Insertion sort

]]>
https://programmerbay.com/program-to-sort-an-array-using-bubble-sort/feed/ 0
C Program to sort an array using Insertion sort in Ascending order https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/ https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/#respond Tue, 09 Jun 2020 18:33:09 +0000 https://www.programmerbay.com/?p=2846 The program sorts an array based on given input. There are bunch of sorting techniques such as Bubble sort, Selection sort and more to achieve this functionality. In this, we’ll be discussion Insertion Sort technique.

Insertion sort

In this sorting technique, the number that needs to be sorted is known as Key. This algorithm is efficient for sorting a small unit of elements.

It can be considered as a way that people use to sort playing cards. A set of cards facing towards the table are picked one by one and put at their correct place.

we compare a new card lifted from the table with the existing ones in our hand.

playing cards

Similarly, in insertion sort at each iteration, an element from the input dataset is taken out and placed to the location where it belongs to be. It is followed until all the inputs get placed and sorted.

Pseudocode

for j=1 to Array.Length

key=arr[j]
k=j-1;
while k>=0 && arr[k]>key
arr[k+1] = arr[k]
arr[k]=key
k= k-1
End While
End for

C program to sort an array using Insertion Sort in Ascending Order

#include<conio.h>
#include<stdio.h>
#define size 6
void main()
{
int arr[size],i,j,k,key,temp;
printf("Please enter elements: \n "); 
for(i=0;i<=size-1;i++)
{
scanf("%d",&arr[i]);
}

for(j=1;j<=size-1;j++)
{
key=arr[j];
k=j-1;
while (k>=0 && arr[k]>key)
{
arr[k+1] = arr[k];
arr[k]=key;
k=k-1;
}
}

printf(" \n Entered Elements :");

for(i=0;i<=size-1;i++)
{
printf("\n %d ",arr[i]);
} 
getch();
}

 

Output:

insertion sort

How does it work?

insertion sort working

It requires a constant amount O(1) of additional memory space and O(n2) comparisons in the worst case and average case to sort an array.

However, sorting time to sort the same size of elements can be varied depending on how much a given array is already sorted.

]]>
https://programmerbay.com/program-to-sort-an-array-using-insertion-sort/feed/ 0
Java Program to Print All Distinct Elements in Array https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/ https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/#respond Thu, 27 Feb 2020 07:16:52 +0000 https://programmerbay.com/?p=6134 Given an array ‘arr’ that may contain duplicate elements and we need to print distinct elements from that array.

In other words, we need to find all the elements from the given array which have exactly occurred once.

Given Input : 

6,6,3,7,2,3,2

Expected output:

7

Java Program to Print All Distinct Elements in an Array

Program:

public class Main {

        public static void main(String[] args) {
            int[] arr = new int[]{6,6,3,7,2,3,2};
            int count;
            boolean flag = false;
            for(int i=0;i<arr.length;i++)
            {
                 count =  1;
                for(int j=0;j<arr.length;j++)
                {
                    if(arr[i] == arr[j] && (i !=j))
                    {
                        ++count;
                        break;
                    }
                }
                if(count==1) {
                    flag = true;

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

            }
            if(flag == false)
                System.out.println("Nothing is unqiue");

        }

}

Output:

blog 5

]]>
https://programmerbay.com/java-program-to-print-unique-elements-of-an-array/feed/ 0
Need of Collection Framework in Java https://programmerbay.com/why-we-need-collections-in-java/ https://programmerbay.com/why-we-need-collections-in-java/#respond Tue, 13 Aug 2019 08:24:06 +0000 https://www.programmerbay.com/?p=4520 When we think about a small piece of data, we always use a variable to store it. Let’s go to a step further, what if we need to store large dataset,  for that purpose, we also have the concept of Array. We can precisely say, an array is used to hold large dataset of the same type having random access capability.

But the downside of the array approach is that it limits the flexibility of handling the data, one of them is the size of the array which cannot be changed at runtime.  It means we cannot expand or shrink the size of an array at the time of program execution, as a result, the probability of memory wastage or insufficient memory allocation can occur. So, we should know the size in advance to confront the size issue. The second disadvantage is that it can only store homogeneous dataset, which is again a problem. This demerit raises the issue of the inability to hold different types of data.

And the last one, the array is not based on some specific standardized data structure, such as Stack, List, this is why there are no inbuilt methods for sorting, searching and more. For each functionality, one requires to write the entire code i.e sorting, searching and so on.

To overcome these problems we use collections which sees a collection of objects as a single entity.

These advantages  are:

  1. The size can be expanded or shrink automatically
  2. It can hold both heterogeneous and homogeneous data. We don’t need to know the size in advance, instead,  it allocates memory dynamically
  3. It is based on standardized data structure and therefore you get inbuilt methods

]]>
https://programmerbay.com/why-we-need-collections-in-java/feed/ 0