Monday 4 September 2017

Java Code to remove the duplicate elements in an ordered array

Problem:

Remove the duplicate elements from an ordered array which are sorted by using selection sort.

Solution:

package array.programs;

import java.util.Arrays;
import java.util.Scanner;

public class RemoveDuplicatesUsingSelectionSort {

int[] array;
int limit;

public static void main(String[] args) {
RemoveDuplicatesUsingSelectionSort selectionSort = new RemoveDuplicatesUsingSelectionSort();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.removeDuplicates(selectionSort.array);
selectionSort.printTheArray();

}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] > array[j]){
position = j;
}
}

temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}

public void removeDuplicates(int[] numbers){
Arrays.sort(numbers);
int j = 0;
int[] temp = new int[numbers.length];
for (int i = 0; i < numbers.length - 1; i++) {
if(numbers[i] != numbers[i+1]){
temp[j++] = numbers[i];
}
}
temp[j++] = numbers[numbers.length - 1];
for (int i = 0; i < temp.length; i++) {
numbers[i] = temp[i];
}
}

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

}


Output:

enter the first array elements limit
5
enter the element
22
enter the element
33
enter the element
2
enter the element
33
enter the element
2
2 22 33 0 0


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...